Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does newline come from when using std::cin after std::cout?

Tags:

c++

Consider the following simple example

#include <iostream> 

int main() 
{
    using namespace std;
    char name[30];        

    cout << "What is your first name: ";
    cin >> name;
    cout << "Hello " << name << endl;

    return 0; 
}

A sample output of this program is as follows:

What is your first name: Bob
Hello Bob

This program works as expected, but I don't understand how the output stream knows to go to the next line. I'm basically thinking of two independent streams of information and am confused as to how the output stream knows to go to the next just because it's followed by input. Where does the newline character come from??

like image 367
Ockham Avatar asked Dec 20 '22 06:12

Ockham


1 Answers

The output stream doesn't go to the next line.

You pressed Enter after typing the name. The terminal has local echo on, which means the characters you enter on the keyboard get echoed to the terminal.

The "Bob" and the newline that you see on the screen are there because you typed them, not because they were sent to cout by your program.

If you used a terminal with local echo turned off, or if you piped input from a file containing Bob, then the output would look like:

What is your first name: Hello Bob
like image 164
M.M Avatar answered Jan 19 '23 00:01

M.M