Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::cin: reading with error checks

std::cin is the standard input stream. Extraction with >> attempts to interpret input as the requested type, so the result of the operation must be checked.

Version: C++23

Syntax

if (std::cin >> value) { /* use value */ }

Include <iostream> and check the whole extraction, for example if (std::cin >> value). Formatted extraction normally skips leading whitespace; extracting a string with >> stops at a separator. std::getline reads an entire line. After a number, a newline may remain in the stream and be consumed immediately by the next line read.

Do not use while (!std::cin.eof()) to predict whether the next read will succeed. End of input or an invalid format can set an error state. For a recoverable error, std::cin.clear() removes flags but does not remove invalid input. std::cin.ignore can discard the rest of the current line; do not retry indefinitely after genuine end of input.

The examples temporarily connect std::cin to a std::istringstream buffer containing fixed text, then restore its previous buffer. This makes the results reproducible without a keyboard. Ordinary input comes from a user or redirection. Successfully reading a number does not validate its business range or establish that no extra characters follow it.

Examples

#include <iostream>
#include <sstream>
#include <string>
#include <limits>

int main() {
    std::istringstream supplied("7 12\nAda Lovelace\n");
    auto* previous = std::cin.rdbuf(supplied.rdbuf());
    int first{}, second{};
    std::string name;
    if (std::cin >> first >> second) {
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        if (std::getline(std::cin, name)) {
            std::cout << first + second << '\n' << name << '\n';
        }
    }
    std::cin.rdbuf(previous);
}

Result

19
Ada Lovelace
#include <iostream>
#include <sstream>
#include <limits>

int main() {
    std::istringstream supplied("wrong\n8\n");
    auto* previous = std::cin.rdbuf(supplied.rdbuf());
    int value{};
    if (!(std::cin >> value)) {
        std::cout << "invalid\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    if (std::cin >> value) std::cout << value << '\n';
    std::cin.rdbuf(previous);
}

Result

invalid
8

Sources