首页 > 解决方案 > Do-While getline 等于 '/n' 并进行输入验证

问题描述

我正在做一个收银机的学校项目。我在输入验证时遇到问题,我有一个 do while 循环,其中用户需要输入任何字符 1 到 6 或按 enter 退出循环,使用 getline(cin,choice) 输入字符。我在验证输入时遇到问题,但仍然允许 '\n' 退出循环,这是我现在的代码

    do {
    cout << "Please enter the number of the item then press enter, press enter to to confirm your order ";
    
    
    
    
    getline(cin, choice);

    while (choice.length() > 1 || choice[0] != '1' && choice[0] != '2' && choice[0] != '3' && choice[0] != '4' && choice[0] != '5' && choice[0] != '6' && choice[0] != '\n') {
        cout << "Invalid Input: please try again\n";
        
        getline(cin, choice);
    }
    
    
    


    switch (choice[0])
    {
    case '1': Hamburger++;
        break;

    case '2': Hotdog++;
        break;

    case '3': Frenchfries++;
        break;

    case '4': Potatochips++;
        break;

    case '5': Cookies++;
        break;

    case '6': Drink++;
        break;

    
    }
    
    }


 while (choice[0] != '\n');

    

Register(Hamburger, Hotdog, Frenchfries, Potatochips, Cookies, Drink);
}

我尝试了多种变体,但没有任何效果,当我按下回车键时,它说这是一个无效的输入。任何帮助都会有所帮助,在此先感谢您。

标签: c++validationinputgetline

解决方案


正如 Andreas Wenzel 所说,解决方案是改变

while (choice[0] != '\n');

while (choice[0] != '\0');

我希望这对其他人有帮助。谢谢你们!


推荐阅读