Reputation: 194
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
Reputation: 249602
Here's a simpler way to write the loop:
while(gradeStream >> grade) {
grades.push_back(grade);
}
Here's how it works:
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.gradeStream >> grade
, i.e. the return value of operator>>(std::istream, int)
, is gradeStream
itself.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).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