+ 4

Input Validation in C++

Hi Sir what to do to stop the user to enter wrong value in int variable means we have defined int variable and user enter "abc..." etc due to which Program crashes. How to stop it ?

10th Apr 2019, 4:06 PM
Muhammad Atif Waheed
Muhammad Atif Waheed - avatar
2 Antworten
+ 4
You could iterate the text input with a for, and chech if each caracter is a digit with isdigit function : #include <iostream> #include <string> #include <ctype.h> using namespace std; int main() {   string s;   cin >> s;   for(char c : s) {     if(! isdigit(c)) {       cout << "error ! input is not a number" << endl;       break;     }   } return 0; }
10th Apr 2019, 6:28 PM
Javier Felipe Toribio
Javier Felipe Toribio - avatar
0
Use std::stol https://en.cppreference.com/w/cpp/string/basic_string/stol but remember to catch exceptions.
10th Apr 2019, 9:00 PM
px16
px16 - avatar