Friday, November 6, 2015

Algorithm: The use of "istringstream"

Here shows some usages of the class "istringstream".

1. Decode sub-strings from a pure char string

e.g.,

       string str = "qq cc ddd";
       istringstream stream(str);
       int a;
       while (stream >> a){
              cout << a << endl;
       }

the sub-string in str is definded as strings separating by ' '. and therefore, the output should be:
qq
cc
ddd

And the loop will terminated automatically when it reaches the end of the str. 

2. Decode sub-strings from a int/char mixed string

       string str = "1, 22, 33";
       istringstream stream(str);
       int a;
       string b;
       while (stream >> a){
              stream >> b;
              cout << a << endl;
              cout << b << endl;
       }


So in this string str, there are int and char. In order to decode the int and char inside, the above code will output
1
,
22
,
33
,


 
 

No comments:

Post a Comment