Stringstream extract integer

假如想象 提交于 2019-11-30 19:39:34

When the stream extracts the last of the 3 digist "1 2 3" the eof state will be set. This is not cleared by the str() member,you need to do it yourself. Change your code to:

ss.clear();
ss.str(Tokens[0]);

Why are you reading into a temp string variable?

You can just read from the stringstream into an int...

int main()
{
    string Digits("1 2 3");
    stringstream ss(Digits);
    int Temp;
    vector<int> Tokens;

    while(ss >> Temp)
        Tokens.push_back(Temp);
}

You have to reset all status flags (eofbit) and bring the stream into a good state (goodbit):

ss.clear(); // clear status flags
ss.str(Tokens[0]);

The reason is that if you keep extracting until the end, you will hit the end, and the eof flag will be set on that stream. After that, read operations will be canceled and you have to clear that flag out again. Anyway, after clearing and resetting the string, you can then go on extracting the integers.

STL! :P

stringstream ss("1 2 3");
vector<int> Tokens;
copy(istream_iterator<int>(ss), istream_iterator<int>(), back_inserter(Tokens));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!