search

Home  >  Q&A  >  body text

c++ - switch语句程序中的一个bug,但就是找不出在哪

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

黄舟黄舟2807 days ago619

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑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

    reply
    0
  • 天蓬老师

    天蓬老师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.

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

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

    reply
    0
  • Cancelreply