10

I'm a C++ beginner and I just wrote this simple program:

#include <iostream>

using namespace std;

int readNumber()
{
    cout << "Insert a number: ";
    int x;
    cin >> x;
    return x;
}

void writeAnswer(int x)
{
    cout << "The sum is: " << x << endl;
}

int main()
{
    int x = readNumber();
    int y = readNumber();
    int z = x + y;
    writeAnswer(z);
    return 0;
}

I don't understand why the output is like this:

Insert a number: 3
Insert a number: 4
The sum is: 7

and not like:

Insert a number: 3Insert a number: 4The sum is: 7

since in the readNumber function there is no endl;.

What am I missing?

(Of course I'm happy with the result I get, but it's unexpected for me)

Pigna
  • 2,792
  • 5
  • 29
  • 51
  • 3
    When you've typed a number, do you press Enter? – Biffen Jan 27 '16 at 11:38
  • 3
    You type `3` and hit enter. Your console doesn't send the input to the program until you hit enter. The output is interleaving with what you typed. Try typing "3 4". – BoBTFish Jan 27 '16 at 11:38
  • 1
    As for knowledge I recommend you to try [**this**](http://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed) as an experiment. – jblixr Jan 27 '16 at 11:45
  • @jblixr since this is beginners question, may get confused with given link. – Anupam Singh Jan 27 '16 at 11:50
  • 3
    This is a good, well-posed _beginner_ question. I like seeing questions like this. +1 for the input, expected output, and code. – erip Jan 27 '16 at 11:51

2 Answers2

18

That's because you push Enter after you enter numbers (-:

First two lines of your "output" aren't pure output. It's mixed with input.

Kyrylo Polezhaiev
  • 1,626
  • 11
  • 18
4

The terminal has a feature/option called echo where it is showing the input as you type. It is by default enabled and causes your own presses of Enter to show up as a newline. In fact, if you had appended an endl after each input, this would have resulted in a blank line appearing after each number. On GNU and many UNIX systems, echo can be disabled using

$ stty -echo

Be careful with this command as you will not be able to see the next commands you are typing (stty echo or reset can be used to enable echo again).

For more information, see this question: How do I turn off echo in a terminal?

Community
  • 1
  • 1
Arne Vogel
  • 6,346
  • 2
  • 18
  • 31
  • While the accepted answer is clear and correct, this one really gets to the bottom of things. Because otherwise there's still, "But why does `Enter` generate a newline, anyway?"--and that's ultimately related to the terminal device itself, rather than just the user's pressing buttons. – Yam Marcovic Jan 27 '16 at 14:39