Tutorials Logic, IN info@tutorialslogic.com

C++ Input and Output with cin, cout, getline, and iomanip

Streams Move Formatted Data

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.

Tokens and Complete Lines

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.

Read a number and a full name

Read a number and a full name
#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";
}
  • The output depends on user input.
  • ignore removes the remainder of the numeric input line.

Formatting Scope

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.

  • Write errors to std::cerr.
  • Check stream state before using extracted values.
  • Do not treat formatted console input as a robust file format.

Input Validation and Stream Recovery

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.

  • Test the extraction expression itself: if (std::cin >> value).
  • Call clear() after a conversion failure, then ignore() through the next newline.
  • Check eof() separately when piped input or a closed terminal should end the program.
  • Use std::quoted, std::fixed, std::setprecision, and std::boolalpha only when the output contract requires them.

Read a bounded integer safely

Read a bounded integer safely
#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.

Before you move on

Stream Review

5 checks
  • Choose token versus line input deliberately.
  • Handle failed extraction.
  • Consume delimiters before getline.
  • Keep formatting effects local.
  • Test empty and malformed input.

Input Questions

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.

Next Step
Next Practice

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.