Problem with re-using a stringstream object

前端 未结 4 1635
孤独总比滥情好
孤独总比滥情好 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:02

    A better way to do this conversion between datatypes would be to use boost::lexical_cast.

    Info and examples can be found at the Boost Site.

    Below is an example of doing an int to string conversion and back (string to int) such as what you're doing in your program.

    #include <string>
    #include <boost/lexcal_cast.hpp>
    
    int main(int argc, char *argv[])
    {
        int i = 42;
        std::string s = boost::lexical_cast<std::string>(i);
        int j = boost::lexical_cast<int>(s);
    
        return 1;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-08 19:27
    cout << "First integer: ";
    getline(cin, input);
    sstream.str(input);
    sstream >> first;     // state of sstream may be eof
    
    cout << "Second integer: ";
    getline(cin, input);
    sstream.str(input);
    sstream.clear();      // clear eof state
    sstream >> second;    // input from sstream
    
    0 讨论(0)
  • 2021-02-08 19:28

    Use sstream.clear(); after sstream >> first;.

    0 讨论(0)
提交回复
热议问题