Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does it wrap without endl;?

Tags:

c++

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)

like image 616
Pigna Avatar asked Jan 27 '16 11:01

Pigna


2 Answers

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?

like image 38
Arne Vogel Avatar answered Sep 28 '22 03:09

Arne Vogel


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.

like image 90
Kyrylo Polezhaiev Avatar answered Sep 28 '22 02:09

Kyrylo Polezhaiev