2013-10-19 33 views
0

我正在为代码编写一个do-while菜单。它使用一个switch语句。 我有问题的问题。我需要代码才能在用户输入大写A - F或小写a - f时运行。现在,while语句只能使用大写字母。我不知何故需要使它适用于小写字母。C++ Do-While循环为Menu。测试大写和小写:

下面的代码:

//display menu 
do 
{ 
    cout << "A. Get the number of values entered \n" 
    << "B. Get the sum of the vaules \n" 
    << "C. Get the average of the values \n" 
    << "D. Get the largest number \n" 
    << "E. Get the smallest number \n" 
    << "F. End the program \n" 
    << "Enter your choice: "; 
    cin >> choice; 

    while (choice < 'A' || choice >'F') 
    { 
     cout << "Please enter a letter A through F: "; 
     cin >> choice; 
    } 
    if (choice != 'F' || 'f') 
    { 
     switch (choice) 
     { 
      case 'A': 
      case 'a': cout << "Number of numbers is: " << numCount << endl; 
       break; 
      case 'B': 
      case 'b': cout << "Sum of numbers is: " << sum << endl; 
       break; 
      case 'C': 
      case 'c': cout << "Average of numbers is: " << average << endl; 
       break; 
      case 'D': 
      case 'd' : cout << "Max of numbers is: " << max << endl; 
       break; 
      case 'E': 
      case 'e': cout << "Min of numbers is: " << min << endl; 
       break; 
      default: cin >> c; 
     } 

    } 
    else  
    { 

     cin >> c; 
    } 
} 

while (choice !='F' || 'f'); 

return 0; 
+4

这个:'while(choice!='F'|| || 'f')'没有做你认为它做的事。它本质上是通过任何合理的优化编译器来评估“while(true)”。它应该是'while(choice!='F'&& choice!='f')'。同样,对于'if(choice!='F'||'f')',它会再次简化为'if(true)'。 – WhozCraig

+0

查看'std :: tolower'或'std :: toupper'来在比较之前将您的角色和文本转换为一个案例。它会简化你的程序。此外,在网上搜索“std :: transform toupper”来获取转换字符串的示例。 –

+0

@WhozCraig请把这个作为答案,我会upvote:D – P0W

回答

3

首先,条件choice != 'F' || 'f'是错误的。 正确的条件是((choice != 'F') && (choice != 'f'))

对于具有小写工作则可以使用这种条件下在while循环:

while (! ((choice >= 'a' && choice <= 'f') || (choice >= 'A' && choice <= 'F'))) 

,或者使用toupper/tolower功能从ctype.h

0

版本1

while ((choice < 'a' || choice > 'f') && (choice < 'A' || choice > 'F')) 

2版

while(choice < 'A' && choice > 'F') 
{ 
    std::cin>>choice; 
    choice = toupper(choice); 
} 

希望有帮助