c++ - 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);
}
我尝试了多种变体,但没有任何效果,当我按下回车键时,它说这是一个无效的输入。任何帮助都会有所帮助,在此先感谢您。
解决方案
正如 Andreas Wenzel 所说,解决方案是改变
while (choice[0] != '\n');
至
while (choice[0] != '\0');
我希望这对其他人有帮助。谢谢你们!
推荐阅读
- python - repl.it 中未显示条形图
- flexbox - 如何计算弹性项目的宽度?以及它如何受其子项宽度的影响?
- javascript - 我是否将我的(大部分)静态网站放在 public/ 文件夹或 index.js 中?
- javascript - 如何从标题中删除 CSS
- mysql - 使用 Unix TimeStamp 格式的数据计算每月行数的 SQL 查询
- javascript - 如何在 JavaScript 中将引用参数作为 PHP 传递?
- node.js - 在 GJS 中使用 Node.js 库
- c - 在矩阵中添加邻居的总和并制作一个新矩阵
- c# - Asp.Net Core 3.x - 如何更改 Linq 表达式以在列表中包含搜索
- python - 设置允许任何客户端连接的服务器