2014-10-02 2 views
-3

이 프로그램에 입력 유효성 검사를 구현하려고하지만 잘못된 결과가 계속 발생합니다. 다른 while 문을 사용해 보았지만 작동하지 않았습니다. 일반적으로해서는 안되는 텍스트를 팝업합니다. 나는 사람이 잘못된 정보를 입력 한 후에 보여주기를 원합니다. 입력 한 데이터가 유효하지 않으면 입력해야합니다.이 코드에 입력 유효성 검사를 통합하려면 어떻게합니까?

여기에 제가 지금까지 가지고있는 코드가 있습니다.

/* 
1. Declare variables for month 1, 2, and 3. 
2. Declare variable for Total and Average Rainfall 
3. Ask user to input name of months. 
4. Then ask user to input inches of rain fall. 
5. Add all inches and then divide by number of inches asked. In this case, 3. 
6. Display average inches of rain for all months to user. 
*/ 

#include <iostream> 
#include <iomanip> 
#include <string> 

using namespace std; 

int main() 

{ 
string month1, month2, month3;//Declared values for months aswell as total and average rainfall. 
double month1Inch, month2Inch, month3Inch; 
double averageInches; 
double totalInches; 
char c = 'y'; 

do 
{ 

    cout << setprecision(2) << fixed; 
    cout << "Enter first month's name:"; 
    cin >> month1; 
    cout << "Enter rain inches for " << month1 << ":"; 
    cin >> month1Inch; 

    cout << "\n"; 

    cout << "Enter second month's name:"; 
    cin >> month2; 
    cout << "Enter rain inches for " << month2 << ":"; 
    cin >> month2Inch; 

    cout << "\n"; 

    cout << "Enter third month's name:"; 
    cin >> month3; 
    cout << "Enter rain inches for " << month3 << ":"; 
    cin >> month3Inch; 

    cout << "\n"; 

    totalInches = (month1Inch + month2Inch + month3Inch); 
    averageInches = (totalInches)/3;//calculating the average 

    //Display calculated data. 
    cout << "The average rainfall for " << month1 << ", " << month2 << ", " << "and " << month3 << " is " << averageInches << endl; 

    cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl; 
    cin >> c; 


} while (c == 'Y'||c=='y'); 

if (c != 'Y' || c != 'y') 
    cout << "you must enter the correct choice" << endl; 

system("pause"); 
return 0; 

} 

는 나는이 "cout을 < <"당신이 하시겠습니까에서 문을 다시 계산하면 퍼팅 시도? 실행하려면 Y를 입력하고 그렇지 않으면 N을 입력하십시오. "< < endl cin >> c;" 하지만 무한 루프가 생깁니다.

오류 코드가 표시되지 않습니다. 그냥 "다시 계산 하시겠습니까?"라는 문구가 나타납니다. 라인과 무한 루프.

데이터를 입력 할 때도 어딘가에 무한 루프가 발생합니다. 그래서 나는 그것을 삭제했다.

+1

그래서 당신이 우리에게 당신이 원하는 것을하려하지 않고 우리에게 당신을 위해 그것을 쓰도록 요청하지 않은 코드를 보여주게되었습니다. SO는 코드 작성 서비스가 아닙니다. –

+0

'main()'에있는 모든 중복 된 주석을 제거하십시오. – blackbird

+0

@Anton Savin, 내가 이전에 작성한 코드를 추가했습니다. – user2221218

답변

1

예 또는 아니오 응답의 유효성을 검사하려는 것 같습니다. 그건 당신이 받아 들일 수있는 입력이있을 때 종료 루프가 필요합니다. 계산을 다시 실행해야 하는지를 결정하는 루프와는 별도입니다.

int main() { 
    // ... 
    do { 
    // ... 

    do { 
     cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl; 
     cin >> c; 
    } while (c != 'Y' && c != 'y' && c != 'N' && c != 'n'); 
    } while (c == 'Y'|| c=='y'); 

    system("pause"); 
    return 0; 
} 
관련 문제