← C++ from Scratch Lesson 50 of 62 · 10 XP

Validating input

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A user can enter anything. If std::cin >> n couldn't read a number, the stream goes into an error state: std::cin becomes false, and all the following reads do nothing.

#include <limits>

int n;
while (!(std::cin >> n) || n < 1 || n > 10) {
    if (std::cin.eof()) return 0;                // the input has ended — leave
    std::cout << "Enter a number from 1 to 10\n";
    std::cin.clear();                            // clear the error flag
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');   // throw away the rest of the line
}

A reliable technique is to read a whole line with std::getline and parse it yourself: then garbage in one line doesn't break the following ones.

Task. A "guess the number" game: the secret number is on the first line. After that the user enters guesses, one per line. For not a number or a number outside 1…100, print invalid; for a smaller one — higher; for a bigger one — lower; for the right one — win in K (K is the number of valid guesses), and finish.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.