C++ User Input

C++ user input is read with std::cin and the >> operator, while output goes to std::cout. Both live in <iostream>.

Reading Values with cin

cin >> reads one value and stops at whitespace. It automatically converts text to the variable's type.

#include <iostream>

int main() {
    int a, b;
    std::cout << "Enter two numbers: ";
    std::cin >> a >> b;
    std::cout << "Sum: " << a + b << '\n';
}
Enter two numbers: 8 5
Sum: 13

Reading a Full Line with getline

std::getline reads everything up to the Enter key, including spaces.

#include <iostream>
#include <string>

int main() {
    std::string name;
    std::cout << "Your full name: ";
    std::getline(std::cin, name);
    std::cout << "Welcome, " << name << "!\n";
}
Your full name: Naeem Amin
Welcome, Naeem Amin!

Formatting Output

The <iomanip> header controls decimals and width. C++20 also adds std::format, which uses {} placeholders.

#include <iostream>
#include <iomanip>

int main() {
    double price = 1234.5678;
    std::cout << std::fixed << std::setprecision(2) << price << '\n';
    std::cout << '[' << std::setw(8) << 42 << "]\n";
}
1234.57
[      42]

Handling Bad Input

If the user types letters when a number is expected, cin enters a fail state. Check it before using the value.

#include <iostream>

int main() {
    int qty;
    std::cout << "Quantity: ";
    if (std::cin >> qty) {
        std::cout << "You ordered " << qty << '\n';
    } else {
        std::cout << "Please enter a number\n";
    }
}
Quantity: abc
Please enter a number

Frequently asked questions

Why does getline skip input after cin?

cin >> leaves the newline in the buffer, and getline reads that empty line. Call std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') before getline, or use std::ws: std::getline(std::cin >> std::ws, s).

How do I print a double with 2 decimal places in C++?

Use std::cout << std::fixed << std::setprecision(2) << value from <iomanip>, or std::format("{:.2f}", value) in C++20.

How do I read a string with spaces in C++?

Use std::getline(std::cin, str), which reads the whole line instead of stopping at the first space.