gpt4 book ai didi

c++ - 使用列表 STL 时出错

转载 作者:行者123 更新时间:2023-11-28 07:55:56 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
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() 但我无法克服错误。任何人都可以识别错误并帮助我找到答案。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com