c++ - 如何在 C++ 中限制用户输入字符串和字符?
问题描述
我正在尝试创建一个小型餐厅程序,我将在其中练习到目前为止我在 C++ 中学到的所有内容。但是我跳进了一个小问题。在程序开始时,我提示用户是否要进入程序,或者选择Y或N退出程序。如果输入的不是其他任何内容,程序将告诉用户无效。
问题是假设用户输入了一个无效字符 a。无效的输出将正常显示,一切看起来都很完美。但如果用户输入两个或更多字符,则无效输出大小写将与用户输入的字符一样多。下面的示例:
#include <iostream>
int main()
{
char ContinueAnswer;
std::string Employee {"Lara"};
std::cout << "\n\t\t\t---------------------------------------"
<< "\n\t\t\t| |"
<< "\n\t\t\t| Welcome to OP |"
<< "\n\t\t\t|Home to the best fast food in Orlando|"
<< "\n\t\t\t| |"
<< "\n\t\t\t--------------------------------------|" << std::endl;
do
{
std::cout << "\n\t\t\t Would you like to enter? (Y/N)"
<< "\n\t\t\t "; std::cin >> ContinueAnswer;
if(ContinueAnswer == 'y' || ContinueAnswer == 'Y')
{
system("cls");
std::cout << "\n\t\t\t My name is " << Employee << "."
<< "\n\t\t\tI will assist you as we go through the menu." << std::endl;
}
else if(ContinueAnswer == 'n' || ContinueAnswer == 'N')
{
std::cout << "\t\t\t\tGoodbye and come again!" << std::endl;
return 0;
}
else
std::cout << "\n\t\t\t\t Invalid Response" << std::endl;
}
while(ContinueAnswer != 'y' && ContinueAnswer != 'Y')
感谢您花时间阅读并感谢任何回答的人:)
解决方案
您可以简单地让用户输入 a string
:
std::string ContinueAnswer;
并像这样比较:
if(ContinueAnswer == "y" || ContinueAnswer == "Y")
它将处理多字符输入。
如果您还想处理输入中的空格,请更改:
std::cin >> ContinueAnswer;
至:
std::getline(std::cin, ContinueAnswer);
推荐阅读
- html - Unity/PowerUI,阿拉伯语文本呈现不同(呈现的字符与输入不同)
- prolog - PROLOG - 检查文件是否存在
- c# - 如何在 C# 中解析来自 GSM 调制解调器的短信
- git - git:解决分支内的提交?
- node.js - 使用 merge2 -npm 流式传输多个任务时在 Gulp 中出现 TypeError
- android - 如何在 Jetpack 中使用导航启动第二个活动
- .net - 在哪里放置 POCO 验证 - N 层架构
- vba - word中的幻影风格
- frameworks - 在 Microsoft Bot Framework 中取消或退出 PromptDialog.Choice 流
- javascript - 如何更改具有相同功能的make js按钮l,例如jsf-button?