dimanche 28 février 2016

Why does my user input only get accepted the second time?

I'm having problems with my first input loop. 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. This happens in my first loop but not my second.

// 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.clear();
        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;

It probably has something to do with cin >> vs. getline, but I don't know how to use getline with my vector/structure. I know I am also 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