Search code examples
c++if-statementconditional-statementscin

Problems with std::cin and isdigit in c++


When I run the code and enters for instance 1 in the terminal it goes to the 'else' condition and breaks. But I'm providing it with a digit so I have trouble understanding why it behaves like that. Could someone help clarify?

int main() 
{
  vector<int> positions;
  int p;
  
  for(int i = 0; i <= 3; i++){
    
    cout << "Enter a number: ";
    cin >> p;
    
    if(isdigit(p)){
      positions.push_back(p);
    } else
    {
      cout << "Please provide numbers from 0 to 100!" <<"\n";
      break;
    }
    
  }
  return 0;
}

Solution

  • the function is defined for the character, it would be true if you wrote isdigit('1').

    Also isdigit(49) = true, because in ascii 49 is digit 1, so isdigit(49) = true;

    check the reference of isdigit(): http://www.cplusplus.com/reference/cctype/isdigit/