在C++ primer plus这本书红的第七单元中有个程序部分如下:
cout << "Enter a character: ";
cin >> ch;
while(ch != 'q') // q to quit
{
cout << "Enter an integer: ";
cin >> times;
n_chars(ch, times); // function with two arguments
cout << "\nEnter another character or press the q-key to quit: ";
cin >> ch;
}
类比于第六单元中的某些程序:
cin.get(ch);
while (ch != '@')
{
......
}
为什么第七单元中该程序要用cin而不是cin.get(ch) 或是 ch = cin.get() 来获取输入呢?
前面的反复练习已经知道cin.get()函数读取所有的输入字符,包括空格和换行符,而cin >> 跳过空格和换行符。当用户对程序提示做出相应时,必须在每行的最后面按下Enter键,以生成换行符。