2011-10-12 50 views
0

我遇到一个问题,程序在运行一次后再次运行它自己。当它运行时,每个选择都正确运行,没有错误,但它永远不会退出程序。任何人?有菜单重新发生的问题。使用switch语句


我觉得哑巴,我把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; 
} 
+0

您的输入是什么?张贴一些输入,因为它适用于我:http://ideone.com/Oe1Mi – Nawaz

+0

请注意,您在那里缺少一些'break'。 –

回答

2

即使它工作在ideone,我想,如果有任何问题,那么问题是的selection类型,使用它意味着通过字符读取字符,包括换行和所有。因此,类型对于selection的更好选择将是int,因为它将只读取整数,跳过可能引发问题的所有其他字符。

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

对了,你忘了使用breakcase '0'

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 
+0

感谢案件0之后的休息。我实际上抓住了现在,当我跑它,因为它会告诉我“0”是无效的,当我选择它作为一个选项 – Luis

+0

@Luis:在那种情况下,我闻到有一些代码的其他问题也是如此。 – Nawaz

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

我觉得你在这里缺少return 0;声明。

+0

如果执行到此处并打印'Goodbye',它将不可避免地遇到'while()'中的条件,这最终会打破循环,这意味着在'0'情况下不需要'return 0' '。 – Nawaz

0

退出对我有用,但你仍然有不正确的最小检查。 (尝试惠特1 3 2)

我会写这样的一部分。

#include <algorithm> 
. 
. 
. 

int m = min(in1,in2); 
m = min(m,in3); 
cout << m; 
+0

无论我输入的数字是多少,最小检查实际上都是完美的。 – Luis

+0

did you try whit 1 3 2? –