dimanche 23 août 2015

Checking for letters in a int

So I'm making an app that requires the user to input a production order(7 digits long) like this:

int order = 0;
cout << "Insert the order number: ";
cin >> ordem;

The question is, how can I prevent the user to enter a letter? Doing that the app just enters a infinite loop. I was thinking in a function like this:

    bool isLetter(int a)
{
   string s = to_string(a);
   for (int i = 0; i < s.size()-1; i++)
   {
     if (isdigit(s[i]))
     {
        return false;
     }
    else
        return true;
  }

}

And then:

if (isLetter(order))
    {
        cout << "Insert only numbers \n";
    }

But it doesn't work. Why? And how can I improve the code?

P.S: I'm very new to programming so, sorry for any beginner mistakes.

Aucun commentaire:

Enregistrer un commentaire