+ 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 ?
2 Respostas
+ 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;
}
0
Use std::stol https://en.cppreference.com/w/cpp/string/basic_string/stol but remember to catch exceptions.