Stan Darsh
Stan Darsh

Reputation: 21

Cin is being ignored in while and for loops

Alright well I'm a newbie with C++ so I'm doing some exercises in Lippman's C++ Primer 5th Edition and the function never even prompts the user for an input. I'm very frustrated as none of my produced code worked and neither does this from an answer key. This only produces "0" when compiled and ran. Any help is appreciated. Compiled on a x64 Mac.

#include <iostream>
int main()
{
    int sum = 0;
    for (int val; std::cin >> val; sum += val);
    std::cout << sum << std::endl;

    return 0;
}

Upvotes: 2

Views: 168

Answers (1)

hyde
hyde

Reputation: 62908

The program works, it just works differently than what you expect!

It expects you to keep entering numbers separted by whitespace, then giving end-of-file (ctrl-Z on Windows, ctrl-d on Unix on empty line) or other invalid input, so that cin goes to fail state.

And when cin goes to fail state, then it gives false to for loop (due to implicit cast to bool using an overloaded bool cast operator), which ends. Then your program prints them sum. If you didn't manage to enter any numbers, then it prints 0, as that is what sum was initialized to.

Upvotes: 1

Related Questions