Uses std::cin.ignore() to Keep the User Typing Until the Input Meets the Requirements

I used to control users' input by making the input a string and process it later. But today, my friend posed this question to me: Can we control input without a char array or string class?

On cppreference.com, I found std::cin.ignore(). This function can help us solve the previous question. Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <limits>

int main() {
int n = 0;
while (true) {
std::cout << "Please input a number: ";
std::cin >> n;
if (!std::cin.good()) {
std::cerr << "Error input." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
} else {
break;
}
}
std::cout << "Your input is: " << n << std::endl;
return 0;
}