我正在研究基于Tamagotchi的控制台(我不能画画,所以我正在使用我所拥有的)。对于我的菜单功能,我正在尝试提供菜单>将用户输入作为char>将char转换为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);
}
截至目前,它不接受输入并执行操作,它只是一遍又一遍地吐出菜单。 所以我的问题是: 1)我是否在正确的轨道上进行转换工作,或者我甚至没有关闭? 2)如果我离开了,你能把我推向正确的方向(鉴于这是可能的)吗?
另外,我知道这可以通过使用int来进行用户选择并传递给交换机来处理。但是,我想看看我是否可以这样做以备将来参考,并尝试在重复的“选项1:”,选项2:“等等方面考虑”开箱即用“。