Home >Backend Development >C++ >How Can I Effectively Verify Integer User Input in C ?
Problem Statement
In a C program, it is crucial to ensure that user input is in the expected format, especially when performing mathematical operations. This article addresses how to determine if the input provided by the user is an integer. If the input is not an integer, the program will prompt the user to re-enter a valid integer.
Solution
There are two main approaches to verify user input as an integer:
1. Using cin.fail():
2. Using std::getline and String Manipulation:
Implementation
Below is a code snippet that implements the std::getline and string manipulation approach:
#include <iostream> #include <string> int main() { std::string theInput; int inputAsInt; std::getline(std::cin, theInput); while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) { std::cout << "Error" << std::endl; if( theInput.find_first_not_of("0123456789") == std::string::npos) { std::cin.clear(); std::cin.ignore(256,'\n'); } std::getline(std::cin, theInput); } std::string::size_type st; inputAsInt = std::stoi(theInput,&st); std::cout << inputAsInt << std::endl; return 0; }
This code continuously prompts the user to enter an integer until a valid integer is entered. It handles situations where the user enters non-numeric characters or provides empty input.
The above is the detailed content of How Can I Effectively Verify Integer User Input in C ?. For more information, please follow other related articles on the PHP Chinese website!