错误:预期在 ‘&’ 之前进行构造函数、析构函数或类型转换代币

发布于 2024-12-14 05:59:10 字数 1121 浏览 0 评论 0原文

我写了以下代码。问题应该是istingstream函数。我做错了什么?提前致谢。

//read a string from input with a istringstream function and output the string   
word by word;
//1.the function takes and returns an istringstream&
//2.the function reads the stream until it hits eof
//the function should print the  contents of an istringstream object
#include <iostream>
#include <string>
#include <sstream>

istringstream& read(istringstream& input)
{

string string, word;
while(getline(input,string), !input.eof())
{
    if (input)      
    {
        istringstream instring(string);
        instring>>word;
        cout<<word<<'_'<<ends;
    }
    if (input.bad())
        throw runtime_error("data is corrupted");
    if (input.fail())
        cerr<<"data failed, try again"<<ends;
    input.close();
    input.clear();
}
return istringstream&;
}

int main ()
{   
    cout<<"enter a string"<<endl;
read(cin);
}

这个输出错误是:(第9行)

 error: expected constructor, destructor, or type conversion before ‘&’ token

I wrote the following codes. The problem should be the istringstream function. what did I do wrong? Thanks in advance.

//read a string from input with a istringstream function and output the string   
word by word;
//1.the function takes and returns an istringstream&
//2.the function reads the stream until it hits eof
//the function should print the  contents of an istringstream object
#include <iostream>
#include <string>
#include <sstream>

istringstream& read(istringstream& input)
{

string string, word;
while(getline(input,string), !input.eof())
{
    if (input)      
    {
        istringstream instring(string);
        instring>>word;
        cout<<word<<'_'<<ends;
    }
    if (input.bad())
        throw runtime_error("data is corrupted");
    if (input.fail())
        cerr<<"data failed, try again"<<ends;
    input.close();
    input.clear();
}
return istringstream&;
}

int main ()
{   
    cout<<"enter a string"<<endl;
read(cin);
}

this output error is: (line 9)

 error: expected constructor, destructor, or type conversion before ‘&’ token

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

彩扇题诗 2024-12-21 05:59:10

更改

return istringstream&;

为:

return input;

但是,如果您不使用返回值,则可以将 read() 的返回类型更改为 void 并且根本不返回任何内容。

Change:

return istringstream&;

to:

return input;

However given you don't use the returned value you could change the return type of read() to void and return nothing at all.

风向决定发型 2024-12-21 05:59:10

所有这些东西都在 std:: 命名空间中定义。

如果你很懒,你可以using namespace std;,但这不是一个好的做法。

All those things are defined in the std:: namespace.

If you are lazy you can using namespace std;, but it's not a good practice.

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