重複の可能性:
これは getline() のバグですか、それとも何か間違ったことをしていますか? 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() を使用してみましたが、エラーを克服できません。誰でもバグを特定して答えを教えてください。