C ++ validation loop issues

I am new to C ++ and very close to a solution, but I still need help. My loop is working correctly for the first time. After that, when I enter the car number, it seems to grab some input somewhere and just perform an 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 fragment of my program, but there is a 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; } 
+6
source share
1 answer

The character '\n' after pressing the enter button in cin >> carNumber[count]; probably remains such that after the second pass getline(cin, carColor[count]); you will get an empty string. One solution is as follows:

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

But a better solution would be to simply change:

 getline(cin, carColor[count]); 

in

 cin >> carColor[count]; 
+4
source

All Articles