程序意图是计算输入流中“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,怎么回事?
cin will consider the input to end when it reads a space, so your
f f
should actually beff
after receiving itThe 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