0

This question was useful: How does while (std::cin >> value) work? but doesn't answer a few of my questions.

When running

#include <iostream>

int main() {

    int sum = 0; int value = 0;

    while (std::cin >> value) {
        sum += value;
    }

    std::cout << sum << std::endl;
}

I then pass something like:

1 2 3 4 5 \n

to the interpreter (I guess not an interpreter, I mean the CLI). My question is how is this stored, how does it "know" to skip the spaces, how are the spaces even processed. I understand it somehow iterates over these but can't quite figure out how... Does it store an intermediate array? Is it perhaps more equivalent to something like this in pseudocode:

input = "1 2 3 4 5 \n"
value = input.get_next() # we look for the next non-space character
if type(value) != int:
    break
else:
    sum += value

also any advice on how I can figure this out by myself would be appreciated.

Alexis Drakopoulos
  • 1,115
  • 7
  • 22
  • What exactly do you mean "how"? If you were to write a program, yourself, to skip spaces when reading an input stream the solution seems obvious: read one character at a time. And skip spaces. The End. And the `>>` overload does the same thing, except that when not skipping spaces the not-skipped digits get converted. Or the stream gets put into a failed state. The End. Which part of this is unclear to you, and what exactly is unclear? – Sam Varshavchik Dec 22 '20 at 15:10
  • My question is how does it "skip spaces", is the input stored as a string? as an array? how does it take in "1 2 3 4 5 \n" and somehow extract the ints to sum? From what I understand it somehow extracts them sequentially until it encounters something that is not an int and then breaks. But I don't understand how it is performing this iteration. – Alexis Drakopoulos Dec 22 '20 at 15:13
  • I am brand new to cpp and I'm essentially confused how me typing "1 2 3 4 5 \n" somehow results in while(std::cin >> value) iterating over the numbers within this input. – Alexis Drakopoulos Dec 22 '20 at 15:15
  • Input streams use stream buffers. [See this question for more information](https://stackoverflow.com/questions/8116541/what-exactly-is-streambuf-how-do-i-use-it). Stream buffers provide an abstraction layer for reading input from an input stream one character at a time, while buffering larger chunks of time, reading one chunk at a time from the file and storing it in an internal buffer. – Sam Varshavchik Dec 22 '20 at 15:15
  • @AlexisDrakopoulos https://en.cppreference.com/w/cpp/io/manip/skipws – Kostas Dec 22 '20 at 15:31

0 Answers0