0

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?

Deep
  • 384
  • 1
  • 4
  • 16

2 Answers2

2

Here

while ( my_stream )

my_stream is convertible to bool and returns true if there's no I/O error.

See: https://en.cppreference.com/w/cpp/io/basic_ios/operator_bool

So, after the last reading, there's no I/O error yet, so it iterates again and there's an error and nothing is read into n in this statement:

my_stream >> n;

And, std::cout prints the last extracted value again i.e. 3.

The solution could be to directly check I/O error after reading in while (preferred):

while ( my_stream >> n )
{
    std::cout << n << '\n';
}

or, print only if the reading is successful using an if:

while ( my_stream )
{
    if ( my_stream >> n ) // print if there's no I/O error
    {
        std::cout << n << '\n';
    }
}

Example (live):

#include <iostream>
#include <sstream>

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

    std::istringstream iss{ a };

    int n {0};

    while ( iss >> n )
    {
        std::cout << n << '\n';
    }

    return 0;
}

Output:

1
2
3

Relevant: Why is "using namespace std;" considered bad practice?

Azeem
  • 7,094
  • 4
  • 19
  • 32
0

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

MikeCAT
  • 61,086
  • 10
  • 41
  • 58