[英]How do I make std::getline inform me when it has hit the end of a stringstream?
[英]Why can't I run my getline code without the stringstream? How do i use stringstream to make this code work?
#include<iostream>
#include<string>
using namespace std;
int main() {
string randomwords,temp;
getline(cin,randomwords);
while(getline(randomwords,temp,' ')) {
cout<<temp<<endl;
}
return 0;
}
std::getline
的第一个参数是std::basic_istream
。 std::basic_string
和std::basic_istream
之间没有转换,因此您不能将std::string
( std::basic_string
的特化)作为第一个参数传递给std::getline
。 这是 C++ 的基本规则,函数的参数必须具有匹配的类型或具有可用于将一种类型的对象转换为另一种类型的几种转换之一。 这里没有,所以这就是它不起作用的原因。
然而, std::basic_istringstream
有一个重载的构造函数,它接受一个std::basic_string
作为参数。 通常可以将其用作隐式转换,但此特定构造函数是explicit
构造函数,禁止将其用于隐式类型转换。 因此,您只需自己完成工作:显式地从字符串构造输入流, std::getline
将愉快地使用它。 任务完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.