JS starter JS starter - 3 months ago 12
C++ Question

C++: Why is my last input not picked up when I use Ctrl+d to end the input loop?

I'm new to C++ and here is my code:

int main(int argc, const char * argv[]) {

vector<double> nums;
double input;
while (cin >> input) {

for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << endl;

return 0;

When the program runs, I input 3 numbers this way:

Enter numbers: 1 2 3

and right after I typed
, I imediately pressed
and the
. However, only two numbers are printed.

If right after I type
, I pressed
enter, ctrl+d, enter
, then three numbers are printed.

I would like to how how to print all 3 numbers regardless of what key I press first. Thanks in advance.


Your C++ code is fine. It's the terminal settings in the shell that are causing this. ^D typed in a Linux terminal (^D implies Unix or a Mac) is not interpreted until a line is submitted. To check that my assertion is correct, make a file like this:

echo -n 1 2 3 > /tmp/stuff.txt

Now double-check that no terminating newline is in the file

cat /tmp/stuff.txt

You'll notice that lack of a newline. Now run your program - which works fine - against the file

./a.out < /tmp/stuff.txt

It worked fine.