Input and Output with cin and cout
Talk to your program: print messages and read what the user types
std::cout sends words and numbers out to the screen, and std::cin reads what the user types in from the keyboard. Together they let your program hold a real conversation.
- print text and numbers with
std::coutand the<<operator, - read the user's input with
std::cinand the>>operator, - chain several
<<or>>in one line, - start a new line with
std::endlor"\n", - write a small interactive program.
1. Printing with std::cout
std::cout (say it "see-out") is the standard output stream. You push text into it with the << operator, and the text appears on the screen. To use it, include the <iostream> library at the top.
#include <iostream>
int main() {
std::cout << "Hello, world!";
return 0;
}
Output:
Hello, world!
The << arrows point toward cout, as if you are pushing the words into the screen.
2. Chaining with <<
You can print several things in one line by chaining <<. You can mix text (in quotes) and numbers (no quotes). The program prints them left to right, with no spaces added for you.
#include <iostream>
int main() {
std::cout << "I am " << 9 << " years old!";
return 0;
}
Output:
I am 9 years old!
Notice the spaces inside the quotes: "I am " and " years old!". If you forget them, the words and numbers stick together like I am9years old!.