c++ - 遇到菜单重新出现的问题。使用 switch 语句

标签 c++ switch-statement

我遇到一个问题,程序在运行一次后再次自行运行。当它运行时,每个选择都正确运行,没有错误,但它永远不会退出程序。有人吗?


我觉得很蠢,我把 while 语句放到它自己重复。好的,现在如果我使用 while 语句,我还需要删除什么才能运行它?


#include <iostream>
using namespace std;

int main()
{
int in1, in2, in3;
char selection;

do
{
cout << "  Welcome to the CS221 Homework 2 Menu\n";
cout << "  ====================================\n";
cout << "  1.  Multiply two integers\n";
cout << "  2.  Divide two integers\n";
cout << "  3.  Check if a number is within the range 10-20\n";
cout << "  4.  Find the minimum of a list of 3 numbers\n";
cout << "\n";
cout << "  0.  Exit\n";
cout << "  ====================================\n";
cout << "  Enter selection: ";
cin >> selection;
cout << endl;

switch (selection)
{
    case '1':
        cout << "Please enter two integers: ";
        cin >> in1 >> in2;
        cout << in1 << " times " << in2 << " is " << (in1 * in2) << endl;
        break;

    case '2':
        cout << "Please enter two integers: ";
        cin >> in1 >> in2;
        cout << in1 << " divided by " << in2 << " is " << ((double) in1 / in2) << endl;
        break;
    case '3':
        cout << "Please enter an integer: " ;
        cin >> in1;
if ( (in1 >= 10) && (in1 <= 20) )
        {
            cout << in1 << " is within the range 10-20.\n";
        }
        else
        {
            cout << in1 << " is NOT within the range of 10-20.\n";
        }
        break;

    case '4':
        cout << "Please enter three integers: ";
        cin >> in1 >> in2 >> in3;
        cout << "The minimum is ";

        if( (in1 <= in2) && (in2 <= in3) )
        {
            cout << in1;
        }
        else if( (in2 <= in1) && (in2 <=in3) )
        {
            cout << in2;
        }
        else
        {
            cout << in3;
        }
        cout << ".\n";
        break;

    case '0':
        cout << "Goodbye.\n";

    default: cout <<selection << "is not a valid menu item.\n";

        cout << endl;
}

}while (selection != '0' );
return 0;
}

最佳答案

即使它在 ideone 工作,我想如果有什么问题,那么问题出在 selectiontype 上,因为使用它意味着逐字符读取,包括换行符和所有。因此,selectiontype 更好的选择是 int,因为它将只读取整数,跳过所有其他可能引起问题的字符。

我建议你将 selection 的类型从 char 更改为 int,并使用 012 等,而不是 '0''1''2'

顺便说一句,你忘了在 case '0' 中使用 break:

case 0: //<--- I changed it from '0' to 0, assuming selection's type is int
    cout << "Goodbye.\n";
    break; //add this line!

不要忘记更改此(以及在所有 case 语句中):

while(selection != 0); //changed '0' to 0

关于c++ - 遇到菜单重新出现的问题。使用 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7735479/

相关文章:

c++ - 在 Visual Studio 2019 C++ 中使用 CPPUnitTest 编写 "DivideByZero"单元测试用例时出现问题

c++ - call/Candidate 没有匹配函数需要 1 个参数,0 提供

C# 在两个数字之间切换?

testing - 如何在 Golang 中将数据发送到 channel 以进行测试?

java - 我添加范围 1 - 9999 条件的代码无法使用 switch 语句运行

c++ - 如何为 C/C++ 传递可选命令行参数?

c++ - 跨多个文件的好友功能

c++ - 需要高级低级编程的书籍和网站建议

c++ - 使用 SDL 的应用程序在任何按键时退出。虽然不应该

python - pyboard : Changing LED colour on USR button press