Input and Output
C++ handles console input and output through streams: cout sends data to the screen, and cin reads data typed by the user.
Printing With cout
The insertion operator << sends values into the output stream, and can be chained to print multiple values in one statement. std::endl inserts a newline and flushes the output buffer.
#include <iostream>
#include <string>
int main() {
std::string name;
int age;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << name << " is " << age << " years old." << std::endl;
return 0;
}
Reading Full Lines
The extraction operator >> stops at whitespace, so it cannot read a full sentence containing spaces. Use std::getline() when you need an entire line of text, such as a full name or address.
std::string fullName;
std::cout << "Enter your full name: ";
std::getline(std::cin, fullName);
std::cout << "Hello, " << fullName << "!" << std::endl;
Common Mistakes
- Using
cin >>to read a name with spaces, which only captures the first word. - Mixing
cin >>andgetline()without clearing the leftover newline character, causing the nextgetline()to read an empty line. - Forgetting
#include <string>when reading into astd::string. - Not prompting the user before reading input, leaving them unsure what to type.
Professional Tip
If you must mix cin >> with getline(), call std::cin.ignore(); once after the last >> read to discard the leftover newline before the next getline().
Your Turn
Write a program that asks the user for their full name (using getline) and their favourite number (using cin), then prints a personalised message combining both.
Mini Quiz
Why might cin >> fail to correctly read someone's full name?
cin >> reads a single whitespace-delimited token, so a name like "Jane Doe" would only capture "Jane". Use std::getline() to read an entire line.