dimanche 28 février 2016

user input validation loop only works on second input

I'm having problems with my input loops. I'm trying to use them to validate input, but I have a problem where entering correct data on the first try still receives an error. Entering that same data a second time will result in true.

// previous cin ^
    // contribution input, checks for numbers only
        cout << "Please enter their contribution amount: ";
        cin.ignore();
        cin >> total[i].contAmount;    // total[i] is a vector of structures
        while (!((total[i].contAmount >= 500) && (total[i].contAmount <= 20000)))
        {
            cout << "Please enter a valid number between 500 and 20000, for example: 14382.53. Only use numerals or periods: ";
            cin.ignore();
            cin >> total[i].contAmount;
        }
    // telephone number input, checks for 10 numbers
        cout << "Please enter their telephone number in this format: 1234567890: ";
        cin.ignore();
        string tempNum;
        getline(cin, tempNum);
        while (!((checkPhone(tempNum, 10)) && (tempNum.length() == 10))) // checkPhone function uses isdigit to check for only numbers
        {
            cout << "Please enter exactly 10 numbers (ex 1234567890): ";
            cin.ignore();
            cin >> tempNum;
        }
        total[i].teleNum = tempNum;

I know I am probably using cin.ignore() improperly, but when I don't use it my code jumps to the next cin without letting the user input anything.

Thanks for your help.

Aucun commentaire:

Enregistrer un commentaire