首页 > 解决方案 > 如何在 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')

感谢您花时间阅读并感谢任何回答的人:)

标签: c++c++11c++14

解决方案


您可以简单地让用户输入 a string

std::string ContinueAnswer;

并像这样比较:

if(ContinueAnswer == "y" || ContinueAnswer == "Y")

它将处理多字符输入。

如果您还想处理输入中的空格,请更改:

std::cin >> ContinueAnswer;

至:

std::getline(std::cin, ContinueAnswer);

推荐阅读