std::cin extracts formatted values from standard input and std::cout inserts values into standard output. Extraction can stop at whitespace, fail on a type mismatch, or leave delimiters for the next operation.
After this lesson you can choose token or line input, detect failbit, discard bad input, and apply formatting without assuming the user typed valid data.
operator>> is appropriate for whitespace-separated tokens. getline reads through a delimiter and is better for names or sentences. When mixing them, remove the pending newline before the first getline.
#include <iostream>
#include <limits>
#include <string>
int main() {
int age{};
std::cout << "Age: ";
if (!(std::cin >> age)) {
std::cerr << "Age must be an integer\n";
return 1;
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::string name;
std::cout << "Full name: ";
std::getline(std::cin, name);
std::cout << name << " is " << age << "\n";
}
Manipulators such as std::fixed and std::setprecision change stream formatting state and can affect later output. Set formatting near the output it controls or save and restore flags in reusable library code.
Formatted extraction with cin succeeds only when the incoming characters can be converted to the requested type. After a failed conversion, the stream sets a failure flag and leaves the invalid input available. Later reads then fail immediately until the program clears the state and discards the bad line.
Validate at the point where data enters the program. A retry loop should explain the accepted range, recover the stream completely, and stop cleanly at end of file. Use getline when spaces are meaningful, then parse the complete line when partial input would be dangerous.
#include <iostream>
#include <limits>
int main() {
int age{};
while (true) {
std::cout << "Age (0-130): ";
if (std::cin >> age && age >= 0 && age <= 130) {
break;
}
if (std::cin.eof()) {
return 1;
}
std::cout << "Enter a whole number in range.\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "Accepted: " << age << '\n';
}
The loop accepts only a complete integer in range and restores cin after invalid text.
Formatted extraction with <code>cin >> value</code> leaves the trailing newline in the input buffer, so the next <code>getline</code> consumes it immediately. Before reading the line, discard that remainder with <code>cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')</code>, or consistently read full lines and parse them.
A failed extraction sets the stream fail state, and later reads do nothing until it is cleared.
By itself, <code>setprecision(n)</code> controls significant digits.
Explore 500+ free tutorials across 20+ languages and frameworks.