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.
This does several things in series, in order, this code:
sline >> n Reads an integer from sline into variable n. Importantly, this also returns sline.
We now effectively have sline >> c which reads a character from sline into variable c.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With