【问题标题】:error using list STL [duplicate]使用列表 STL 时出错 [重复]
【发布时间】:2012-10-04 13:02:59
【问题描述】:

可能重复:
Is this a bug with getline(), or am I doing something wrong. Right way to use getline()?

我尝试在 STL 列表和字符串上学习这个主题。所以作为一个集成,我尝试了这个程序:

#include<iostream>
#include<list>
#include<string>
using namespace std;

int main(){
    list<string> obj1, obj2;
    string obj;
    int n;
    cout<<"Enter the number of elements in string list 1:\t";
    cin>>n;
    cin.clear();
    cout<<"Enter the string:\n";
    for( int i=0; i<n; i++){
        getline(cin, obj);
        cout<<"The string is:\t"<<obj<<" and i is "<<i<<endl;
        obj1.push_back(obj);
    }
    obj1.sort();
    cout<<"The string in sorted order is:\n";
    list<string>::reverse_iterator rit;
    for( rit = obj1.rbegin(); rit != obj1.rend(); rit++)
        cout<<*rit<<endl;
    return 0;
}

我得到以下输出:

Enter the number of elements in string list 1:  4
Enter the string:
The string is:   and i is 0
goat
The string is:  goat and i is 1
boat
The string is:  boat and i is 2
toad
The string is:  toad and i is 3
The string in sorted order is:
toad
goat
boat

程序中的错误是第一个字符串是一个空白字符串,它会自动插入到列表中。为了避免这种情况,我尝试使用 cin.clear() 但我无法克服错误。任何人都可以请找出错误并帮助我回答。

【问题讨论】:

  • ios::clear 方法重置错误标志,但不包含该流

标签: c++ list stl


【解决方案1】:

在同一程序中使用operator&gt;&gt;getline 时必须特别小心。 operator&gt;&gt; 在输入流中留下一个行尾指示符,getline 接受。

尝试在getline 之前添加std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n')

【讨论】:

    【解决方案2】:

    cin.clear() 不会做你认为的那样。查一下。然后按照您在 Rob 的回答中得到的建议进行操作。

    【讨论】:

      【解决方案3】:

      这是因为你输入数字后,换行符还在缓冲区中,所以第一个getline 得到了那个换行符。最简单的解决方案是在循环之前使用一个虚拟的getline 调用。

      【讨论】:

        猜你喜欢
        • 2014-07-06
        • 2011-04-21
        • 1970-01-01
        • 2021-10-06
        • 1970-01-01
        • 2017-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多