Isdigit () always passes validation

Hello, I want to check my program if the user instead of entering a number, if he typed something that is not a number.

so i made this function

void ValidationController::cinError(int *variable){

    if(!isdigit(*variable)){
        cin.clear();
        cin.ignore(256, '\n');
        cout <<*variable<<endl;
        *variable=0;
        cout <<*variable<<endl;
    }
}

I call the function as follows:

int more;
cin >>more;
cinError(&more);

So my problem is that every time I give a number, it acts as if I did not. It goes inside if it makes the variable equal to zero. What am I missing here?

+4
source share
2 answers

, isdigit , , isdigit , int. stream >> , .

, string, isdigit , :

string numString;
getline(cin, numString);
for (int i = 0 ; i != numString.length() ; i++) {
    if (!isdigit((unsigned char)numString[i])) {
        cerr << "You entered a non-digit in a number: " << numString[i] << endl;
    }
}
// Convert your validated string to `int`
+8

isdigit

, ? ( dasblinkenlight, )

  cin.exceptions(ios_base::failbit); 
  int more;
  try
  {
    cin >> more;
    if (!isspace(cin.get()))
       /* non-numeric, non-whitespace character found
         at end of input string */
      cout << "Error" << endl;
    else
      cout << "Correct" << endl;
  }
  catch(ios_base::failure& e)  
  {        
  /* non-numeric or non-whitespace character found                    
   at beginning */
    cout << "Error" << endl;
  }
+2

All Articles