#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0; // use basic input
cout << "Enter characters; enter # to quit:\n";
cin >> ch; // get a character
while (ch != '#') // test the character
{
cout << ch; // echo the character
++count; // count the character
cin >> ch; // get the next character
}
cout << endl << count << " characters read\n";
return 0;
}
以上代码循环完成字符的输入
以下是其中一种输出结果:
Enter characters; enter # to quit:
see ken run#really fast
seekenrun
9 characters read
分析:为什么程序输出时忽略了空格呢?
解释:原因在cin。cin读取时将忽略空格和换行符。因此输入中的空格没有被回显,也不包括计数。
另外发送给cin的输入将会被缓存,只有按下回车键之后输入才会被送进程序。