Whippet
Whippet

Reputation: 322

CIN Loop Not Working

EDIT:

Ctrl-D

terminates buffer in linux.

Ctrl-Z

in Windows.

I should add I use Linux. I use g++.

Now, I'm learning C++ by way of C++ Primer Edition 4.

In an example, this code is given:

#include <iostream>
    int main()
    {
        int sum = 0, value;
        // read till 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;
     }

Now, I enter "3 4 5 6", and I press enter, all I get is a newline, like:

1 2 3 4 5
Blank line

No output at all.

I refuse to use concepts I haven't learned yet, so far I know no cin.METHOD functions, so what's the problem?

Upvotes: 1

Views: 196

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 546073

Input and output are buffered. End the input to terminate the loop by pressing Ctrl+Z in the console.

Or read from a file:

echo '1 2 3 4 5' > foo.txt
./your-program < foo.txt

Or read from standard input via a pipe:

echo '1 2 3 4 5' | ./your-program

or:

./your-program <<< '1 2 3 4 5'

(Depending on the terminal emulator you’re using.)

Upvotes: 3

Related Questions