1. 程式人生 > >C++ premier Plus書之--C++之cin.get介紹, 二維陣列

C++ premier Plus書之--C++之cin.get介紹, 二維陣列

看個簡單的例子 

#include "iostream"
using namespace std;

int main() {
	char ch;
	int count = 0;
	cout << "Enter characters;  enter # to-quit" << endl;
	cin >> ch;
	while (ch != '#')
	{
		cout << ch;
		++count;
		cin >> ch;
	}
	cout << endl << count << " characters " << endl;
	return 0;
}

隨便輸入字元, #字元為結束, 執行結果為:

從執行結果可以看到, 空白字元(這裡是空格), 並沒有當作字元進行輸出

為什麼程式沒有把空格顯示出來呢?

原因是在cin讀取char值時, 與讀取其他基本型別一樣, cin將忽略空格和換行符, 因此輸入的空格沒有被回顯.

更為重要的是, 傳送給cin的輸入被緩衝, 這意味著, 只有在使用者按下回車鍵後, 輸入的內容才會被髮送給程式, 這也就是為什麼執行程式的時候, 可以在#後面輸入字元的原因.

使用 cin.get()進行修改

#include "iostream"
using namespace std;

int main() {
	char ch;
	int count = 0;
	cout << "Enter characters;  enter # to-quit" << endl;
	cin.get(ch);
	while (ch != '#')
	{
		cout << ch;
		++count;
		cin.get(ch);
	}
	cout << endl << count << " characters " << endl;
	return 0;
}

這裡我們使用cin.get(char) 來接收字元, 看一下輸出結果:

 

從執行結果可知cin.get(char), 將接收下一個字元, 無論字元是不是空格

 

二維陣列

看一下二維陣列的初始化:

int nums[4][5] = 
{
	{1, 2, 3, 4, 5},
	{11, 12, 13, 14, 15},
	{21, 22, 23, 24, 25},
	{31, 32, 33, 34, 35}
};

看一個簡單的例子

#include "iostream"
using namespace std;

const int Cities = 5;
const int Years = 4;
int main()
{
	const char * cities[Cities] = 
	{
		"Gribble City",
		"Gribbletown",
		"New Gribble",
		"San Gribble",
		"Gribble Vista"
	};
	
	int maxtemps[Years][Cities] = 
	{
		{1, 2, 3, 4, 5},
		{11, 12, 13, 14, 15},
		{21, 22, 23, 24, 25},
		{31, 32, 33, 34, 35}
	};
	
	cout << "maximum temperatures : " << endl;
	for (int city = 0; city < Cities; city++)
	{
		cout << cities[city] << "\t";
		for (int year = 0; year < Years; year++)
		{
			cout << maxtemps[year][city] << "\t";
		}
		cout << endl;
	}
	
	return 0;
}

 程式執行結果為:

注意在c++中我們如果向定義一個字串陣列, 除了上面demo中的方法外, 還可以有以下幾種方法:

char cities[Cities][25] = 
	{
		"Gribble City",
		"Gribbletown",
		"New Gribble",
		"San Gribble",
		"Gribble Vista"
	};

或者:
string  cities[Cities] = 
	{
		"Gribble City",
		"Gribbletown",
		"New Gribble",
		"San Gribble",
		"Gribble Vista"
	};

從空間的角度來說 char陣列的陣列比較浪費空間, 而是用char型指標陣列比較節省空間, 如果要修改陣列中的字串, 則二維陣列是更好的選擇, 而是用string字串陣列則比兩者都要方便.