Search code examples
c++splitistringstream

Split string by commas using istringstream


I tried this code which can split the string by comma:

string spa ="12,233,434,2";
istringstream iss(spa + ",");
int val;
char dot =',';
while(iss >> val >> dot){
     cout << val << endl;
} 

But I have no idea how it works. It seems to extract the value firstly, then right-shifts?


Solution

  • iss >> val >> dot reads an int and a char, which happens to match the format of the input.

    Their values prior to reading doesn't matter at all.

    The while tests if the read was successful, and stops when the input fails.