mercredi 28 septembre 2016

Error handling doubles with strings in C++

My assignment is to take test grades of students in a class room and return the highest, lowest, and the average. I am currently debugging for error that could be entered by the user. I have successfully fixed issues when the user inputs characters for the decimal test score values. What I'm having trouble with is if the user inputs "4k" the program excepts the 4 as a valid input but still gives the error when the program shouldn't approve the score as a valid input but should error and prompt for only numeral values.

I'll provide an output example

heres the code segment:

for (int i = 0; i < students; i++)
      {

        cout << "Please enter a score: " << flush;
        cin >> array[i];
        do{

          if(cin.fail())
          {
            cin.clear();
            cout<<"Error, that's not a decimal number. Please reenter: ";
            std::cin.ignore(numeric_limits<streamsize>::max(), '\n' );
            cin >> array[i];
          }
        }while(cin.fail());

      }

Sample output error::

How many students are in class? 3
Please enter 3 scores
 - - - - - - - - - - -
Please enter a score: jkl
Error, that's not a decimal number. Please reenter: jkl
Error, that's not a decimal number. Please reenter: 4k
Please enter a score: Error, that's not a decimal number. Please reenter: 0
Please enter a score: 3
4
0
3
The worstest score in the class is: 0
The bestest score in the class is: 4
The average score is: 2.33333

Aucun commentaire:

Enregistrer un commentaire