Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 菜单字符输入到int_C++ - Fatal编程技术网

C++ 菜单字符输入到int

C++ 菜单字符输入到int,c++,C++,我正在做一些基于控制台的Tamagotchi的东西,我不能画,所以我在用我现有的东西。对于我的菜单函数,我试图呈现一个菜单>以字符形式接收用户输入>将字符转换为int>执行选择 #include <iostream> //Functions void menuShow(); int menuChoice(); void menuAction(); int main() { menuAction(); } //Menu display void menuShow() {

我正在做一些基于控制台的Tamagotchi的东西,我不能画,所以我在用我现有的东西。对于我的菜单函数,我试图呈现一个菜单>以字符形式接收用户输入>将字符转换为int>执行选择

#include <iostream>

//Functions
void menuShow();
int menuChoice();
void menuAction();

int main()
{
    menuAction();
}


//Menu display
void menuShow()
{
    std::cout << "\nPlease choose from the following:" << std::endl;
    std::cout << "(S)tatus of your pet." << std::endl;
    std::cout << "(F)eed your pet." << std::endl;
    std::cout << "(Q)uit." << std::endl;
}

//Convert input from char to int
int menuChoice()
{
    char userChoice;
    int convertChoice = 0;

    do
    {
        menuShow();
        std::cout << "Choice: ";
        std::cin >> userChoice;
        if ((userChoice = 'S') || (userChoice = 's'))
        {
            convertChoice = 1;
        }

        else if ((userChoice = 'F') || (userChoice = 'f'))
        {
            convertChoice = 2;
        }

        else if ((userChoice = 'Q') || (userChoice = 'q'))
        {
            convertChoice = 3;
        }

    } while ((userChoice != 'S') || (userChoice != 's') || (userChoice != 'F') || (userChoice != 'f') || (userChoice != 'Q') || (userChoice != 'q'));    //Repeat if incorrect selection is made

    return convertChoice;    //return converted int
}

//Get converted choice and perform related action
void menuAction()
{
    int choice;
    do
    {
        choice = menuChoice();    //initialize using returned convertChoice
        switch (choice)
        {
        case 1:
            std::cout << "You look at your pets' stats" << std::endl;
            break;

        case 2:
            std::cout << "You feed your pet" << std::endl;
            break;

        default:
            std::cout << "You have quit!" << std::endl;
            break;
        }
    } while (choice != 3);
}
到目前为止,它不接受输入并执行操作,它只是一次又一次地弹出菜单。所以我的问题是:我是否在正确的轨道上工作,或者我还没有接近?2如果我走远了,你能把我推向正确的方向吗


另外,我知道这可以通过使用int进行用户选择并传递给交换机来解决。但是,我想看看我是否可以这样做以供将来参考,并尝试从重复选项1:、选项2:,等等的角度进行思考。

使用调试器时,执行每条语句时会发生什么,一次一个称为单步执行?请在比较之前将选择变量转换为小写或大写。请参阅std::tolower和std::toupper。您也可以看看如何使用开关进行tha输入。使用早期返回或可能中断可能有助于避免重复使用如此长且容易出错的循环条件。可以在if语句中使用中断语句退出循环。为什么要将选择转换为数字?你可以跳过这一步,通过信件来处理它们。switch语句也适用于字符。