使用列表 STL 时出错
error using list STL
可能的重复项:
这是 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(),但我无法克服错误。任何人都可以识别错误并帮助我找到答案。
在同一
程序中使用 operator>>
和 getline
时必须特别小心。operator>>
在输入流中留下一个行尾指示器,getline
接受该指示器。
尝试在getline
之前添加std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n')
。
cin.clear()
不会做你认为它做的事情。查一查。然后按照你在 Rob 的回答中得到的建议。
这是因为输入数字后,换行符仍在缓冲区中,因此第一个getline
获得该换行符。最简单的解决方案是在循环之前使用虚拟getline
调用。
相关文章:
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 在C应用程序中运行C++(带有STL)函数
- 为什么 stl 字符串C++函数有时出错有时会出错?
- STL 容器在函数中作为模板参数,在调用中出错
- 将 lambda 传递给 STL 集时出错"bad function call"
- 使用列表 STL 时出错
- stl:map插入值时出错
- 将"using namespace boost::numeric::ublas;"与 stl 矢量一起使用时出错
- 自定义迭代器和 STL 算法出错
- C++在使用转换(STL)时出错