简体   繁体   中英

std::stringstream - string to number working

I am learning C++ and I'm in doubt on how the following code works. My aim is to accept numbers (as a std::string) from the Command Line separated by spaces and separate these numbers from the string. I posted another question related to this and got the program working using the code below. Can you please explain to me how the numbers are actually extracted from the strings?

string gradesFullLine;
getline(cin, gradesFullLine);
stringstream gradeStream(gradesFullLine);

for(gradeStream >> grade; gradeStream; gradeStream >> grade) {
    grades.push_back(grade);
}

Here's a simpler way to write the loop:

while(gradeStream >> grade) {
    grades.push_back(grade);
}

Here's how it works:

  1. gradeStream >> grade invokes operator>>(std::istream, int) (or whatever numeric type grade is). This attempts to "extract" a number from the stream, and updates the "stream state" indicating success or failure.
  2. The result of the expression gradeStream >> grade , ie the return value of operator>>(std::istream, int) , is gradeStream itself.
  3. Any standard stream has a method equivalent to operator bool() const which lets you use the stream in a boolean context, such as an if() or while() condition. This operator returns true if the stream is "good" meaning it has not had any I/O errors (including reading past the end of the stream).
  4. So the boolean value is used as the while condition, meaning that the loop will be entered so long as gradeStream has a "good state" which means grade has been populated with a number extracted from the stream (how this extraction happens is defined by your particular system implementation).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM