🔁 C++ Input and Output – cout and cin Explained
Want to talk to your program and make it talk back? That’s where input and output come in! 💬💻
In C++, we use:
cout
– to print/output thingscin
– to get input from the user
🖨️ Output with cout
cout
(short for “character output”) is used to display messages on the screen. It uses the insertion operator <<
.
#include <iostream> using namespace std; int main() { cout << "Welcome to C++ I/O!" << endl; cout << "Let's learn how to print and take input." << endl; return 0; }
⌨️ Input with cin
cin
(short for “character input”) is used to get data from the user. It uses the extraction operator >>
.
Let’s write a program that asks for your name and greets you:
#include <iostream> using namespace std; int main() { string name; cout << "Enter your name: "; cin >> name; cout << "Hello, " << name << "!" << endl; return 0; }
🧠 Explanation
cout
is used to display messages.cin
stores the user’s input into a variable.string name;
declares a variable to store a name.endl
is used to move to a new line (like hitting “Enter”).
⚠️ Note:
cin
reads input only until the first space. For full line input, we use getline()
(you’ll learn that soon!).