【问题标题】:istringstream not working when the line has been taken as input from console but working with a file当该行已从控制台作为输入但使用文件时,istringstream 不起作用
【发布时间】:2011-12-20 06:28:20
【问题描述】:

这是我用来从控制台读取输入的代码。它使用字符串流读取第一行,它还从该字符串中读取单词,但之后它就崩溃了。

如果我从文件中获取输入而不是标准输入,则同样的事情适用于文件。然后相同的代码可以正常工作而不会崩溃。我无法理解问题所在。

int main()
{
    string line;

    set<string> dict;
    vector<string> file;
    vector< vector<string> > message;

    while(true)
    {
        getline(cin,line);
        if(line.at(0) == '/' && line.at(1) == '/')
            break;
        else
            dict.insert(line);
    }
    int i =0;
    istringstream stream;
    while(true)
    {   
        getline(cin,line);
        cout<<line<<endl;
        stream.str(line);
        string words;
        while(stream >> words)
        {
            message[i].push_back(words);
            cout<<words<<" ";
        }
        cout<<"Reached out of the first loop"<<endl;
        i++;
    }

    cout<<"The dictionary input is"<<endl;
    set<string>::iterator it;
    for(it = dict.begin();it!=dict.end();it++)
        cout<<*it<<endl;
    cout<<endl;

    int vec_size = message.size();
    for(i = 0;i<vec_size;i++)
    {
        int inner_size = message[i].size();
        for(int j= 0;j<inner_size;j++)
            cout<<message[i][j]<<" ";
        cout<<endl;
    }

    system("pause");
    return 0;
}

我给出的输入是

//字典 字符串1 字符串2 字符串3 //信息 12345 67 xc23 bgv34 090ds 3ndlk

我想将 //message 之前的单词读入一组字符串 以及//message 之后的单词到一个 2D 向量中,其中每一行包含已在第一行中添加的单词

如果我从文件中获取此输入,则它可以正常工作,但不能使用来自控制台的输入。

【问题讨论】:

  • 当它崩溃时它会说什么?另外,能否请您发布一个完整的、可编译的和可执行的重现崩溃的示例?
  • 请发布short, self contained, correct 示例,而不是sn-p
  • @BjörnPollex 它什么也没说,我得到的消息是程序已停止工作。实际上我没有使用任何调试器,我只使用 Dev C++ 编译器。

标签: c++ string stream iostream


【解决方案1】:

我认为你应该使用 ostringstream。将东西放入其中,最后从流中创建一个 std::string ,这就是您要在此处执行的操作。

【讨论】:

    猜你喜欢
    • 2014-08-04
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2018-07-05
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多