2016-03-05 21 views
-6

我不知道如何拒絕無效輸入的考試和作業(有效數字是0.00 - 100.00)。但我還需要給用戶一個機會來輸入有效的輸入。所以如果他們在同一個變量中連續放入兩個無效輸入,它會告訴用戶他們需要重新啓動程序並阻止它運行。林編程新,所以我不是很擅長這一點。我如何拒絕我的代碼中的無效輸入?

#include <iostream> 
#include <string> 
#include <iomanip> 
using namespace std; 

int main() 
{ 
float exam_1; 
float exam_2; 
float exam_3; 
float assignment_1; 
float assignment_2; 
float weighted_exam = .1667; 
float weighted_assignment = .25; 
float min_score = 0.00; 
float max_score = 100.00; 
string name; 

cout << "Please enter student name <First Last>: "; // this will ask for the students first and last name 
getline(cin, name); 

cout << "\n"; 

cout << "\t Be sure to include the decimal point for scores.\n"; 

cout <<"\t !!! All scores should range from 0.00 to 100.00!!! \n"; 

cout << "\t For example: 80.50 \n"; 

cout << "\n"; 

cout << "Please enter your exam 1 score: "; 
cin >> exam_1; 

cout << "Please enter your exam 2 score: "; 
cin >> exam_2;          

cout << "Please enter your exam 3 score: "; 
cin >> exam_3;           

cout << "Please enter your assignment 1 score: "; 
cin >> assignment_1;        

cout << "Please enter your assignment 2 score: "; 
cin >> assignment_2; 

cout << endl;       

cout << "-" << "OUTPUT" << "-\n"; 

return 0; 
} 
+0

你應該做的更微乎其微,濃縮版本的代碼應該只關注問題。你不能指望我們讀所有這些代碼.. –

回答

0

你可以這樣做:

do{ 
    cout <<"\t !!! All scores should range from 0.00 to 100.00!!! \n"; 
    cin >> exam_1; 
while(exam_1 < 0.0 || exam_1>100.0); 

重複這對所有輸入

+0

好吧生病嘗試。 –

+0

@DanielTeichler,這種方式你會問一個有效的值,直到用戶把一些聽起來正確的東西! –

0
cout << "Please enter your exam 1 score: "; 
cin >> exam_1; 

cout << "Please enter your exam 2 score: "; 
cin >> exam_2;          

cout << "Please enter your exam 3 score: "; 
cin >> exam_3;           

auto ReadExamScore = [](auto& ex, char c) 
{ 
    cout << "Please enter your exam " << c << " score: "; 

    for (int i = 0; i < 2; i ++) 
    { 
      if (cin >> ex) 
      { 
       if (ex>= 0.0 && ex <= 100.00) 
        return true; 
      } 

      cout << "Please enter a valid exam score" << endl; 
    } 

    cout << "Press any key to exit..." << endl; 
    getchar(); 
    exit(0); 
}; 

ReadExamScore(exam_1,'1'); 
ReadExamScore(exam_2,'2'); 
ReadExamScore(exam_3,'3');