为什么我可以在没有弦乐的情况下运行我的Getline代码?如何使用StringStream使此代码起作用?

发布于 2025-02-13 17:12:50 字数 275 浏览 0 评论 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;
}
#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦开始←不甜 2025-02-20 17:12:50

std :: getline的第一个参数是std :: basic_istreamstd :: basic_stringstd :: basic_istream之间没有转换std :: Basic_string)作为std :: getline的第一个参数。这是C ++的基本规则,函数的参数必须具有匹配类型,或具有几种可用于将一种类型对象转换为另一种类型的对象之一。这里没有,所以这就是为什么它不起作用的原因。

但是,std :: Basic_istringStream具有一个重载的构造函数,该构造函数将std :: Basic_string作为参数。通常,它可以用作隐式转换,但是该特定的构造函数是explicit构造函数,该构建器禁止将其用于隐式类型转换中。因此,您将自己完成工作:明确地从字符串构建输入流,std :: getline将很乐意使用它。任务完成了。

std::getline's first parameter is a std::basic_istream. There is no conversion between a std::basic_string and a std::basic_istream, so you cannot pass a std::string (a specialization of std::basic_string) as a first parameter to std::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 a std::basic_string as a parameter. Normally that can be used as an implicit conversion, but this particular constructor is an explicit 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, and std::getline will happily use it. Mission accomplished.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文