Home >Backend Development >C++ >How to Validate Numeric Input in C Beyond `atoi()`?
Validating Numeric Input in C
In a program that processes integer input, ensuring that users provide valid numbers is crucial. Unfortunately, the atoi() function falls short when dealing with multi-digit integers. This article explores alternative methods to verify numeric input.
Using the failbit
C 's input stream (cin) sets the failbit when it encounters input it cannot parse. This can be leveraged to validate input as follows:
int n; cin >> n; if(!cin) { // User did not input a number cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); }
Handling Input Overflow
When integers exceed the maximum allowed value, cin also sets the failbit. To prevent this, check the stream state before reading the input:
while(!cin.eof()) { int n; cin >> n; if(!cin) { // Input error occurred cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } else { // Valid input process(n); } }
This loop continues reading and validating input until the end of file (EOF) is reached.
Other Alternatives
The above is the detailed content of How to Validate Numeric Input in C Beyond `atoi()`?. For more information, please follow other related articles on the PHP Chinese website!