how to read stringstream with dynamic size?

谁都会走 提交于 2019-12-04 02:38:40

You get the extra c at the end because you don't test whether the stream is still good after you perform the extraction:

while (ss)        // test if stream is good
{
    ss >> var;    // attempt extraction          <-- the stream state is set here
    cout << var;  // use result of extraction
}

You need to test the stream state between when you perform the extraction and when you use the result. Typically this is done by performing the extraction in the loop condition:

while (ss >> var) // attempt extraction then test if stream is good
{
    cout << var;  // use result of extraction
}

The while(ss) condition check in your code checks if the last read from the stream was successful or not. However, this check is going to return true even when you have read the last word in your string. Only the next extraction of ss >> var in your code is going to make this condition false since the end of the stream has been reached & there is nothing to extract into the variable var. This is the reason you get an extra 'c' at the end. You can eliminate this by changing your code as suggested by James McNellis.

Manoj R

There is also a member function good() which tests if the stream can be used for I/O operations. So using this the above code can be changed into

while(ss.good())  // check if the stream can be used for io
{
    ss >> var;    // attempt extraction          <-- the stream state is set here
    cout << var;  // use result of extraction
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!