我如何拒绝代码中的无效输入?

时间:2016-03-05 17:58:03

标签: c++

我不知道如何拒绝考试和作业的无效输入(有效数字为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;
}

2 个答案:

答案 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);

对所有输入重复此操作

答案 1 :(得分: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');