2013-10-19 2 views
0

코드에 대한 do-while 메뉴를 작성 중입니다. switch 문을 사용합니다. 질문은 이고,입니다. 사용자가 대문자 A - F 또는 소문자 a - f를 입력 할 때만 실행되는 코드가 필요합니다. 지금 while 문은 대문자에서만 작동합니다. 나는 어쨌든 소문자에서도 잘 작동 할 필요가있다.C++ Do-While 루프. 대문자와 소문자 모두 테스트 :

//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 대답을 넣어주세요. D – P0W

답변

3

먼저, 조건 choice != 'F' || 'f' 잘못 :

여기에 코드입니다. 올바른 조건은 ((choice != 'F') && (choice != 'f'))입니다. 당신이 while 루프에서이 조건을 사용할 수 있습니다 소문자와 작품에 대한

:

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

또는 ctype.h

0

버전에서 toupper/tolower 기능을 사용하여 1

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

버전 2

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

도움이 되길 바랍니다.

관련 문제