Input (cin)
Overview
Interactive applications require dynamic user input. While std::cout pushes data out to the terminal, std::cin (character input stream) pulls data in from the user's keyboard.
It utilizes the 'Extraction Operator' (>>), which extracts characters from the input stream and automatically formats them into the appropriate variable type. However, cin has a severe limitation: it fundamentally stops reading the moment it hits a 'whitespace' (like a space or a newline). This makes it great for reading single numbers or words, but terrible for reading full sentences.
Syntax
#include <iostream>
#include <string>
int main() {
int age;
std::string firstName;
std::cout << "Enter your age: ";
// 1. Extracts the number and stores it in 'age'
std::cin >> age;
std::cout << "Enter your first name: ";
// 2. Extracts the text and stores it in 'firstName'
std::cin >> firstName;
return 0;
}Common Pitfalls
- Trying to read a full sentence with
cin. If a user types 'John Doe',cin >> namewill only capture 'John'. The ' Doe' is left sitting in the input buffer, which will instantly ruin your nextcincall. - Input Type Mismatch. If you run
cin >> age;(an integer) and the user types 'Hello', the input stream violently fails, enters an error state, and ignores all future input commands until you manually clear the error flags.
Interview Questions
Instead of the >> operator, you must use the std::getline() function. For example: std::getline(std::cin, fullName);. This reads the entire stream until the user presses Enter, capturing all spaces perfectly.
Real-World Example
The classic 'cin buffer bug'. When you mix cin >> and getline(), the newline character from hitting 'Enter' breaks the application.
#include <iostream>
#include <string>
int main() {
int age;
std::string fullName;
std::cout << "Age: ";
std::cin >> age;
// BAD: The user pressed 'Enter', leaving a '\n' in the buffer!
// FIX: You MUST discard the leftover '\n' before calling getline!
std::cin.ignore();
std::cout << "Full Name: ";
std::getline(std::cin, fullName);
return 0;
}Check Your Knowledge
Test your understanding of Input (cin) with these quick questions.