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?