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字符串数组则比两者都要方便.

猜你喜欢

转载自blog.csdn.net/c1392851600/article/details/84350128