Babbzzz
Babbzzz

Reputation: 194

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);
}

Upvotes: 0

Views: 96

Answers (1)

John Zwinck
John Zwinck

Reputation: 249602

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, i.e. 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).

Upvotes: 4

Related Questions