c++sstream

sstream string wrong output


I am trying to read a string of three number using sstream but when I try to print them, I am getting a wrong output with four numbers.

Code:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    string a("1 2 3");

    istringstream my_stream(a);

    int n;

    while(my_stream) {
        my_stream >> n;
        cout << n << "\n";
    }
}

Output:

1
2
3
3

Why I get four numbers in the output compared to three numbers in input string?


Solution

  • You are printing the data before checking if readings are successful.

        while(my_stream) {
            my_stream >> n;
    

    should be

        while(my_stream >> n) {
    

    Related (doesn't seem duplicate because eof() isn't used here):
    c++ - Why is iostream::eof inside a loop condition (i.e. while (!stream.eof())) considered wrong? - Stack Overflow