【问题标题】:Why this cin is not working properly? [duplicate]为什么这个 cin 不能正常工作? [复制]
【发布时间】:2014-11-20 09:51:28
【问题描述】:
#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;
}

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

谢谢!

PS:我尝试将fflush(stdin) 放在 getline 之前,但它也没有帮助。

【问题讨论】:

  • 不要将stdioiostreams 混用。
  • 我删除了stdio.h 并使用cin 代替scanf(我这样做只是为了让它工作)但它仍然没有。
  • 这不是答案,只是一般建议。
  • 下次请准备MCVE。整个问题可以用一个 10 行的程序来概括。

标签: c++ cin


【解决方案1】:

scanf 从输入中读取数字,并留下一个换行符。该换行符由下一个 getline 解释,一开始你会得到一个空行。

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

而不是只读取数字:

scanf("%d", &t);

使用以下也吞下换行符:

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

无论如何,将stdioiostream 混合使用是个坏主意,但如果你使用,你会得到类似的结果

cin >> t;

修复 2(也适用于流):忽略 getline 读取的第一行


修复 3

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

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

【讨论】:

  • 我没听懂你。您是否建议在获取字符串数量后放置一个额外的scanf。顺便说一句,即使你输入cin 而不是scanf,它仍然不起作用。
  • @sarah 更新得更准确
  • 但是,为什么会这样呢?我已经删除了stdio,但它并没有解决问题。我可以删除第一行,但为什么会发生这种情况?
  • 答案的第一句话就是这样。
  • 我在问,cin 也会发生这种情况吗? cin 是否表现出相似的性质?
猜你喜欢
  • 2012-04-01
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-30
  • 2023-02-20
  • 1970-01-01
相关资源
最近更新 更多