c++ - switch语句程序中的一个bug,但就是找不出在哪
黄舟
黄舟 2017-04-17 12:09:03
0
2
606

程序意图是计算输入流中“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,怎么回事?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
巴扎黑

cin will consider the input to end when it reads a space, so your f f should actually be ff after receiving it

Peter_Zhu

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.

  1. cin >> x, ignore spaces and carriage returns and consider the input to end

  2. cin.get() and cin.getline(), do not ignore spaces

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template