Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the logic behind while(sline >> n >> c && c== ',')?

vector<int> ParseLine (string line){
  istringstream sline(line);

  char c;
  int n;
  vector<int> row;
  while(sline >> n >> c && c == ",")
        row.push_back(n);

  return row;
}

This is one of the functions to read 2d vector from the file. I was wondering the logic behind the while loop.

like image 253
Necati Yesil Avatar asked Dec 31 '22 01:12

Necati Yesil


1 Answers

This does several things in series, in order, this code:

  1. sline >> n Reads an integer from sline into variable n. Importantly, this also returns sline.

  2. We now effectively have sline >> c which reads a character from sline into variable c.

  3. The && operator returns true only when both sides are true. sline >> c will once again return sline which will evaluate to true as long as there are characters left to read.

  4. c == "," Checks that c is a comma. This should probably be changed to c == ',' so that its a character == character comparison instead of a comparison between a character and a string.

  5. Then in the loop body the integer n is appended to the vector row. This saves the integer so that when we return row at the end this integer will be an element.

The overall effect is that a string of comma separated integers is interpreted as a vector of integers. Note that this code should work for vectors with any number of elements, but only if there is a comma after every number. (E.G. "45, 52, 4," but not "45, 52, 4")

like image 64
Trevor Galivan Avatar answered Jan 11 '23 22:01

Trevor Galivan