0

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);
}
3
  • 1
    An input stream is an input stream, it doesn't matter if it's a file input stream, std::cin or a string input stream. Reading data is the same for all input streams. So getting a value from your gradeStream is no different from getting a value from std::cin. Commented Jan 5, 2015 at 9:04
  • But if you want to know the technical details, then read about std::num_get::get. Commented Jan 5, 2015 at 9:05
  • Thanks for the link Jo. I am going through it. :) Commented Jan 5, 2015 at 11:07

1 Answer 1

4

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).
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. :) You guys make me want to learn to code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.