Problem with re-using a stringstream object

前端 未结 4 1640
孤独总比滥情好
孤独总比滥情好 2021-02-08 18:43

I\'m trying to use safe practices in handling input with numbers only in C++, so I use a stringstream object as so:

#include 
#include 

        
4条回答
  •  忘了有多久
    2021-02-08 19:03

    You need to reset the state of the stringstream. Generally, this involves two steps: clearing the buffer:

    sstream.str("");
    

    and resetting the error state flags:

    sstream.clear();
    

    If you don't clear the buffer, if you get an input like "123abc" then "abc" will still be in the stream when you try to read from it the next time.

    You should also make sure to test the fail state of the stream (sstream.fail()) to ensure that the extraction was successful. If you want to be sure that the user only entered an integer (i.e., you want to prevent the user from inputting, say, "123abc", then you should test to make sure sstream.eof() is true.

提交回复
热议问题