简体   繁体   中英

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() .

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

On Windows, use ^Z ( Ctrl Z ) 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM