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??
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
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