c++ - 为什么这个 cin 不能正常工作?

标签 c++ cin

<分区>

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main (void)
{

    int c;
    cout<<"enter number of test cases\n";
    cin>>c;
    while (c!=0)
    {
        string s;
        int t;
        cout<<"enter number of strings to be entered\n";
        cin>>t;
        map <string,int> a;
        map <string,int>::iterator it;    
        while ( t!= 0 )
        {
            getline(cin,s);
            it = a.find(s);
            if ( it == a.end() )
            {
                a.insert(pair<string,int>(s,1));
                cout<<"New inserted\n";
            }
            else
            {
                a[s]++;
                cout<<"Value incremented\n";
            }
            t--;
        }
        it = a.begin();
        cout<<"Value will print\n";
        while ( it != a.end() )
        {
            cout<<it->first<<" "<<it->second<<"\n";
            it++;
        }
        c--;
    }
    return 0;
}

所以,我编写了这段代码,首先询问测试用例,然后询问字符串的数量,然后对字符串进行排序并输出它们的频率。 现在,在这段代码中,当我在输入字符串数量后按下回车键时,会显示消息 New Inserted,这意味着新行将作为字符串放入 map 中。为什么会这样?

谢谢!

PS:我尝试将 fflush(stdin) 放在 getline 之前,但它也无济于事。

最佳答案

scanf 从输入中读取数字,并在后面留下一个换行符。该换行符由下一个 getline 解释,您首先得到一个空行。

修复 1: 使用 scanf 读取换行符:

而不是只读取数字:

scanf("%d", &t);

使用下面的也吞下换行符:

scanf("%d\n", &t);

无论如何,将 stdioiostream 混合使用是个坏主意,但如果您使用

cin >> t;

修复 2(也适用于流):忽略 getline

读取的第一行

修复 3

使用getline将数字转化为字符串并解析:

getline(cin, s);
istringstream ( s ) >> t; 

关于c++ - 为什么这个 cin 不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26041702/

相关文章:

c++ - Visual Studio 中的这些 .pch 和 .ncb 文件是什么?

c++通过双换行符拆分字符串

放置 cin.get 后关闭 C++ 控制台

c++ - 代码片段在某些情况下有效,但不符合预期,为什么?

c++ - 输入 cin C++ 没有任何内容

c++ - 怎么把电脑画的图旋转90度

c++ - 来自 Mat 图像的 OpenCV 子图像

c++ - 从 cin 读取 int 数字,直到按下 ESC C++

c++ - std::cin 输入带空格?

c++ - 为什么 MQL4 会错过一个循环中的迭代?