简体   繁体   English

C ++验证循环问题

[英]C++ validation loop issues

I'm pretty new to c++ and am really close to the solution, but I still need some help. 我对c ++还是很陌生,确实很接近解决方案,但是我仍然需要一些帮助。 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;

}

The '\\n' character after you press enter in cin >> carNumber[count]; 按下Enter键后,输入'\\n'字符cin >> carNumber[count]; probably still remains so after you execute the second pass of getline(cin, carColor[count]); 在执行getline(cin, carColor[count]);的第二遍之后,可能仍然存在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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM