c++for-loopstringstream

Using stringstream inside a loop to extract a number from few strings


I'm currently practicing with stringstreams to extract values from a string. In this simple code, user enters a name and a number (separated by a space), this string is stored in input. Then, it's passed to stream and it separates the name and the number, which are stored in name and number. Then, the number is output with std::cout. This process is done a few times with different names and numbers.

#include <sstream>
#include <iostream>

int main() {
    std::string input;
    std::stringstream stream;
    std::string name;
    double amount;

    for (;;) {
        std::getline(std::cin, input);      // enter a name, a whitespace and a number
        stream.str(input);
        stream >> name >> amount;           // problem here
        std::cout << amount << std::endl;
    }
    return 0;
}

Problem: Only the number of the first entered input is stored in amount. The numbers of the next inputs will not be stored in amount (amount always has the same number inside). Maybe, there is something I don't know about stringstreams...


Solution

  • Problem: Only the number of the first entered input is stored in "amount". The numbers of the next inputs will not be stored in "amount" (amount always has the same number inside). Maybe, there is something I don't know about stringstreams...

    Yes. You have forgot to reset the std::stringstream after you used once.

    In order to do that, you need to set both the underlying sequence(contents of a stringstream) to an empty string using std::stringstream::str and also the fail(if any) and eof flags with clear.

    That means, end of your for loop you need this: SEE LIVE

    int main()
    {
       ....
       ....
       for (;;)
       {
          ...
          ...
          stream.str( std::string() );   // or stream.str(""); 
          stream.clear();
       }
       return 0;
    }