Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ validation loop issues

Tags:

c++

validation

I'm pretty new to c++ and am really close to the solution, but I still need some help. My loop works correctly the first time. After that when I enter the car number, it seems to be grabbing some input somewhere and just executes the invalid color on the second pass. Obviously, I'm missing something, but I'm at a loss. Any help would be appreciated.

This is just a small snippet of my program, but there lays the problem:

while (count < 3)
{
    cout << endl << "Enter car color: blue, red or green in lower case.  ";
    getline(cin, carColor[count]);

    if (!(carColor[count] == "blue" || carColor[count] == "red" || carColor[count] == "green"))
    {
        cout << "That is an invalid color"
            << "The program will exit";
        cin.clear();
        cin.ignore();
        return 0;
    }


    cout << endl << "Enter car number between 1 and 99: ";
    cin >> carNumber[count];                   // Enter car number
    if (carNumber[count] >99 || carNumber[count] < 1)
    {
        cout << "That is not a correct number"
            << " The program will exit";
        return 0;
    }

    cout << "car no is:" << carNumber[count] << "color: " << carColor[count];


    ++count;
//  int lapCount{ 1 };

    cout << endl;

}
like image 695
Caridore Avatar asked Apr 17 '16 02:04

Caridore


1 Answers

The '\n' character after you press enter in cin >> carNumber[count]; probably still remains so after you execute the second pass of getline(cin, carColor[count]); you get an empty string. One solution is to do this:

char c;
cin >> carNumber[count];
cin >> c;

But better solution would be just to change:

getline(cin, carColor[count]);

to:

cin >> carColor[count];
like image 200
Pooya Avatar answered Nov 03 '22 01:11

Pooya