2014-04-16 167 views
1

我的問題是我如何驗證getTestScore函數的數據?需要程序告訴用戶invalid data, please enter a score in between 0 and 100,如果他們輸入的是負數或超過100的數字。謝謝。驗證功能

#include <iostream> 
using namespace std; 
//function prototypes 
float getTestScore(); 
float calcAverage(float score1, float score2, float score3); 
int main() 
{ 
    float s1, s2, s3; //these variables are used to store test scores 
    float average; 
    //call getTestScore function to get the test scores 
    s1 = getTestScore(); 
    s2 = getTestScore(); 
    s3 = getTestScore(); 
    //call calcAverage to calculate the average of three test scores 
    average = calcAverage(s1, s2, s3); 

    //display the average 
    cout << "average of three test scores(" << s1 << "," << s2 << "," << s3 <<  ")is"  << average << endl; 
    return 0; 
} 

//function definitions/implementation getTestScore function gets a test score from the user and 
//validates the score to make sure the value is between 0 and 100. if score is out of range 
//getTestScore function allows the user to re-enter the score. This function returns a valid score 
// to the caller function 
float getTestScore() 
{ 
    float score = 0; 
    do 
    { 
     cout << "Enter test score: " << endl; 
     cin >> score; 
    } while (!(score >= 0 && score <= 100)); 

    return score; 
} 

// calcAverage function calculates and returns the average of the three test scores passed to 
//the function as input. 
float calcAverage(float score1, float score2, float score3) 
{ 
    float average; 
    average = (score1 + score2 + score3)/3; 

    return average; 
} 
+0

http://isocpp.org/wiki/faq/input-output#istream-and-ignore – chris

回答

0

您可以更改while循環這樣的:

float getTestScore() 
{ 
    float score = 0; 
    while ((cout << "Enter test score: ") 
        && (!(cin >> score) || score < 0 || score > 100)) { 
     // This part only gets executed on invalid input 
     cout << "invalid data, please enter a score in between 0 and 100 "; 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
    } 
    return score; 
} 
0

通過使用「Do-While」,在檢查輸入之前至少執行一次代碼塊。

第一個輸入因此不會被你的病情檢查:

while (!(score >= 0 && score <= 100)); 

使用標準while循環,因此檢查前手這個條件應該可以解決你的問題。