Topic 9 of 83
Input (cin)
Overview
Taking input allows programs to be interactive. `std::cin` reads input from the standard input stream (keyboard) and uses the extraction operator `>>`.
Syntax
cpp
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age; // Reads an integer
return 0;
}Common Pitfalls
- Using `cin >> stringVar` to read a full sentence. It will only capture the first word.
- Input stream failure: If you ask for an `int` and the user types `"abc"`, `cin` enters a fail state and stops reading future inputs until cleared.
Interview Tips
- Explain how `cin` handles whitespace. It stops reading when it hits a space, tab, or newline.
- Know how to use `getline(cin, stringVar)` to read an entire line of text including spaces.
Real-World Example
Taking multiple inputs at once.
example
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string first, last;
cout << "Enter first and last name: ";
cin >> first >> last; // Chains input
cout << "Hello, " << first << " " << last << "!" << endl;
return 0;
}