Why does my program not output:
10
1.546
,Apple 1
instead of
10
1
<empty space>
here's my program:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main () {
string str = "10,1.546,Apple 1";
istringstream stream (str);
int a;
double b;
string c, dummy;
stream >> a >> dummy >> b >> dummy >> c;
cout << a << endl;
cout << b << endl;
cout << c << endl;
return 0;
}
Basically I am trying to parse the comma-separated strings, any smoother way to do this would help me immense.
I could manage to change my code a little. Didn't implement
0x499602D2
method yet, but here is what worked for me.In IOStreams, strings (meaning both C-strings and C++ strings) have virtually no formatting requirements. Any and all characters are extracted into a string only until a whitespace character is found, or until the end of the stream is caught. In your example, you're using a string intended to eat up the commas between the important data, but the output you are experiencing is the result of the behavior I just explained: The
dummy
string doesn't just eat the comma, but also the rest of the character sequence until the next whitespace character.To avoid this you can use a
char
for the dummy variable, which only has space for one character. And if you're looking to putApple 1
into a string you will need an unformatted extraction because the formatted extractoroperator>>()
only reads until whitespace. The appropriate function to use here isstd::getline()
:Clearing the newline after the formatted extraction is also necessary which is why I used
std::ws
to clear leading whitespace. I'm also using anif
statement to contain the extraction in order to tell if it succeeded or not.You can set the classification of the comma character to a whitespace character using the
std::ctype<char>
facet of the locale imbued in the stream. This will make the use of a dummy variable unnecessary. Here's an example:Allow me to suggest the following.
I don't consider it 'smoother', as cin / cout dialogue is not 'smooth', imho.
But I think this might be closer to what you want.
Results: (and, of course, you need not do anything with the commas.)
10 ','
1.546 ','
Apple 1
You should do the below changes:
And
In your example, dummy would have got the string ",1.546,Apple" . Because till a non-numeric char is encountered, it is fed to variable a. After that everything is added to dummy ( a string ) until the default delimiter (space) is reached