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)
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With