← Вернуться к курсу: Modern C++ from scratch

Console input and output

Видео скоро появится

A useful program talks to its user: it asks for data and shows results. You already know std::cout for output; now we see std::cin to read from the keyboard, std::getline to read whole lines with spaces, and the right way to validate what the user types. This is one of the areas where beginners stumble most, so we go slowly and keep the typical mistakes in view.

Reading with std::cin

The >> operator extracts a value from the input stream and stores it in the variable, interpreting it according to its type. It skips leading whitespace and stops at the next space or newline. That is why std::cin >> name reads only one word. You can chain reads: std::cin >> a >> b reads two values separated by spaces or newlines.

cpp
#include <iostream>
#include <string>

int main() {
    std::string name;
    int age{};

    std::cout << "Your first name: ";
    std::cin >> name;
    std::cout << "Your age: ";
    std::cin >> age;

    std::cout << "Hello, " << name << "! Next year you will be "
              << age + 1 << ".\n";
    return 0;
}

Whole lines with getline

To read a whole line, spaces included, use std::getline(std::cin, text). There is a well known trap: after reading a number with >>, the newline you typed with Enter stays pending in the buffer. If you call getline right after, it reads that empty line and the program seems to skip the question. The fix is to discard the rest of the line with std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') before using getline. You need to include <limits> for that constant.

cpp
#include <iostream>
#include <limits>
#include <string>

int main() {
    int quantity{};
    std::cout << "Quantity: ";
    std::cin >> quantity;

    // discard the newline left by the previous >>
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::string title;
    std::cout << "Product title: ";
    std::getline(std::cin, title);

    std::cout << quantity << " x " << title << '\n';
    return 0;
}

Validating input

If the user types 'abc' when an int was expected, the stream enters an error state: the read fails, the variable becomes 0 and all later reads fail too until you repair it. You can detect it because the stream itself converts to bool: if (std::cin >> n) is true only if the read succeeded. To recover call std::cin.clear() and discard the bad line with ignore. With this pattern you can ask for a number until it is valid.

cpp
#include <iostream>
#include <limits>

int readPositiveInt(const char* prompt) {
    int value{};
    while (true) {
        std::cout << prompt;
        if (std::cin >> value && value > 0) {
            return value;
        }
        if (std::cin.eof()) {
            return 0;   // input ended, give up
        }
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Please type a positive whole number.\n";
    }
}

int main() {
    int n = readPositiveInt("How many items? ");
    std::cout << "You asked for " << n << " items\n";
    return 0;
}

A classic problem appears when mixing std::cin >> with std::getline. The >> operator reads the value but leaves in the stream the newline you typed with Enter; if you then call getline, it finds that newline immediately and returns an empty string, as if the program skipped your question. The fix is to discard the rest of the line before calling getline: std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); (it needs to include <limits>). A simpler option is to always read whole lines with getline and convert afterwards with std::stoi or std::stod.

And if the user types text where you expected a number, cin enters an error state and all later reads fail silently. Always check the result of the read with if (std::cin >> n) and, on failure, reset the stream with std::cin.clear() and discard the line with ignore before asking for the value again. Validating input is what separates an exercise program from one that can truly be used.

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →