菜单重新出现时出现问题.使用switch语句

Have an issue where menu is re-occurring. using switch statement

本文关键字:问题 使用 switch 语句 新出现 菜单      更新时间:2023-10-16

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


我觉得自己很笨,我放了while语句,这样它就重复了。好的,现在如果我取while语句,我还需要取下什么才能运行它?


#include <iostream>
using namespace std;
int main()
{
int in1, in2, in3;
char selection;
do
{
cout << "  Welcome to the CS221 Homework 2 Menun";
cout << "  ====================================n";
cout << "  1.  Multiply two integersn";
cout << "  2.  Divide two integersn";
cout << "  3.  Check if a number is within the range 10-20n";
cout << "  4.  Find the minimum of a list of 3 numbersn";
cout << "n";
cout << "  0.  Exitn";
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上工作,我想如果有任何问题,那么问题就出在selection类型上,因为使用它意味着逐字符读取,包括换行符和所有字符。因此,selection类型的更好选择是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
case '0':
        cout << "Goodbye.n";

我想你这里遗漏了return 0;声明。

Exit对我有效,但您仍然有不正确的最小检查。(试试whit 1 3 2(

我会这样写那部分。

 #include <algorithm>
 .
 .
 .
 int m = min(in1,in2);
 m = min(m,in3);
 cout << m;