当该行已从控制台作为输入但使用文件时istringstream不工作

时间:2011-11-02 12:07:47

标签: c++ string stream iostream

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

同样的工作文件如果不是stdin,我从文件中获取输入。然后相同的代码工作而不会崩溃。我无法理解问题所在。

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;
}

我正在输入

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

我想把//之前的单词读成一组字符串 和//消息之后的单词进入2D向量,其中每行包含已在第一行添加的单词

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

1 个答案:

答案 0 :(得分:0)

我认为你应该使用ostringstream。把东西放入其中,最后在流中创建一个std :: string,这就是你想要在这里做的。