user3002473
user3002473

Reputation: 5074

C++ std::cout not writing anything to the console

Forgive me for my noobishness as I have only just begun learning C++, but I came across something that's confusing me. The following code is me following along the examples from the C++ Primer 5th Edition PDF found here.

#include<iostream>
int main(){
    int sum = 0, value = 0;
    while (std::cin >> value)
        sum += value;
    std::cout << "Sum is: " << sum << std::endl; //this doesn't do anything
    std::cin.ignore().get();
    return 0;
}

Now for some reason, the last std::cout statement doesn't do anything at all, and it's perplexing me as aside from the std::cin.ignore().get() this is the exact same as the example in the pdf and yet this doesn't do anything. What confuses me the most is that if I write value from inside the while loop you can observe that it doesn't recur infinitely; it stops like it should after the last input value, so the error shouldn't be in the execution of the while loop.

Any help is appreciated, thanks!

EDIT: I'm using Visual Studio 2013 Ultimate

EDIT2: The input I'm using is 3 4 5 6

EDIT3: For comparison's sake, here is the code from C++ Primer 5th Edition:

#include <iostream>
int main()
{
     int sum = 0, value = 0;
     // read until end-of-file, calculating a running total of all values read
     while (std::cin >> value)
         sum += value; // equivalent to sum = sum + value
     std::cout << "Sum is: " << sum << std::endl; return 0;
}

So the ONLY difference between mine and this is the std::cin.ignore().get().

Upvotes: 0

Views: 518

Answers (1)

Jun Zhou
Jun Zhou

Reputation: 3080

while (std::cin >> value) means it will not stop until failed to read an integer, i.e encountering an EOF or a non-integer input.

On Windows, use ^Z (CtrlZ) to enter an EOF.

Try input:

1 2 3 4
^Z

It should hit the cout line. And it's totally a different question about the cin.ignore() stuff.

Upvotes: 5

Related Questions