c++ - Parsing integer from comma delimited string -


i'm new c++ , trying find example code extract integers comma delimited strings. come across code:

std::string str = "1,2,3,4,5,6"; std::vector<int> vect;  std::stringstream ss(str);  int i;  while (ss >> i) {     vect.push_back(i);      if (ss.peek() == ',')         ss.ignore(); }   

i have trouble understanding while loop conditional statement: ss >> i. understanding, istream::>> returns istream operated on. error bits may set operation. there doesn't seem boolean variable involved. how can ss >> i serve conditional statement?

additionally, >> extract 1 or multiple characters? example, if have string "13, 14". operation return integers 1, 3, 1, 4 or integers 13, 14?

thanks lot, m

1) conditional statement.

std::stringstream derives std::ios, defines:

  • in c++ 98 / c++ 03: operator void*() const

description: null pointer if @ least 1 of failbit or badbit set. other value otherwise.

  • in c++ 11: explicit operator bool() const

description: true if none of failbit or badbit set. false otherwise.

that's why can use expression condition loop - operator>> returns reference stringstream object, converted either void* pointer or bool, depending on supported c++ version.

more info this: std::ios::operator bool

2) operator>> applied numbers extracts many characters can:

int main() {     std::string str = "111,12,1063,134,10005,1226";     std::vector<int> vect;      std::stringstream ss(str);      int i;      while (ss >> i)     {         vect.push_back(i);          if (ss.peek() == ',')             ss.ignore();     }      return 0; } 

content of vector: [111, 12, 1063, 134, 10005, 1226].

again, more info: std::istream::operator>>


Comments

Popular posts from this blog

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

sorting - opencl Bitonic sort with 64 bits keys -