C++ 使用列表STL时出错

C++ 使用列表STL时出错,c++,list,stl,C++,List,Stl,可能重复: 我试着在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 ele

可能重复:

我试着在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;
}

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

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


尝试将
std::cin.ignore(std::numeric_limits::max(),'\n')
添加到
getline

cin.clear()
之前。它不会做您认为它会做的事情。查一查。然后按照Rob回答中的建议进行操作。

这是因为在输入数字后,换行符仍在缓冲区中,因此第一个
getline
将获得该换行符。最简单的解决方案是在循环之前使用伪
getline
调用。

ios::clear
方法重置错误标志,但该流不包含
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