程序意图是计算输入流中“ff”字符的数量,程序如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int Cnt=0;
bool flag = false;
string s;
while (cin>>s)
for(auto ch:s)
switch (ch)
{
case 'f':
if (flag == true)
++Cnt;
flag = true;
break;
default:
flag = false;
break;
}
cout << "There are "<< Cnt << " ff(s)." << endl;
return 0;
}
问题在于我输入f f
(中间有空格,所以不算计数),输出仍然是1,怎么回事?
巴扎黑2017-04-17 12:11:03
cin will consider the input to end when it reads a space, so your f f
should actually be ff
after receiving it
天蓬老师2017-04-17 12:11:03
The three input methods of cin in the ostream class are different. The cin class reads characters one by one from the program's input buffer queue. The end point of the character is determined based on the accepted data type.
cin >> x, ignore spaces and carriage returns and consider the input to end
cin.get() and cin.getline(), do not ignore spaces