When I try to extract valid numbers from an input using istringstream
I get the follwoing misbehavior from istringstream
:
For Example:
void extract(void)
{
double x;
string line, temp;
getline(cin, line);
istringstream is(line);
while(is >>temp)
{
if(istringstream(temp) >>x)
{std::cout<<"number read: "<<x<<endl;}
}
}
Input:
1 2 3rd 4th
Output:
number read: 1
number read: 2
number read: 3
number read: 4
The misbehavior is istringstream converting the string 3rd
to the number 3.
Why does istringstream
do this and how can one avoid this?
It's because you read numbers from the stream.The
>>
operator extracts"3rd"
from the stream, and tries to convert it to adouble
, but since only the first character of the string is a number, it can only parse the"3"
and simply discard the non-digit characters.If you want
"3rd"
then you need to read it as a string.