为什么我可以在没有弦乐的情况下运行我的Getline代码?如何使用StringStream使此代码起作用?
#include<iostream>
#include<string>
using namespace std;
int main() {
string randomwords,temp;
getline(cin,randomwords);
while(getline(randomwords,temp,' ')) {
cout<<temp<<endl;
}
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main() {
string randomwords,temp;
getline(cin,randomwords);
while(getline(randomwords,temp,' ')) {
cout<<temp<<endl;
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
std :: getline
的第一个参数是std :: basic_istream
。std :: basic_string
和std :: basic_istream
之间没有转换std :: Basic_string
)作为std :: getline
的第一个参数。这是C ++的基本规则,函数的参数必须具有匹配类型,或具有几种可用于将一种类型对象转换为另一种类型的对象之一。这里没有,所以这就是为什么它不起作用的原因。但是,
std :: Basic_istringStream
具有一个重载的构造函数,该构造函数将std :: Basic_string
作为参数。通常,它可以用作隐式转换,但是该特定的构造函数是explicit
构造函数,该构建器禁止将其用于隐式类型转换中。因此,您将自己完成工作:明确地从字符串构建输入流,std :: getline
将很乐意使用它。任务完成了。std::getline
's first parameter is astd::basic_istream
. There is no conversion between astd::basic_string
and astd::basic_istream
, so you cannot pass astd::string
(a specialization ofstd::basic_string
) as a first parameter tostd::getline
. This is a fundamental rule of C++, parameters to functions must have matching types or have one of several conversions that can be used to convert an object of one type to the other one. There are none here, so that's why it won't work.However,
std::basic_istringstream
has an overloaded constructor that takes astd::basic_string
as a parameter. Normally that can be used as an implicit conversion, but this particular constructor is anexplicit
constructor which prohibits it from being used in implicit type conversions. Therefore you'll just do the job yourself: construct an input stream from a string explicitly, andstd::getline
will happily use it. Mission accomplished.