[Solved] C++ show me how stop this while infintie loop


You said:

I get an infinite loop when user does not enter a number

Create a function that prints the prompt, tries to read the number, if reading doesn’t succeed, clears the input stream and calls itself again.

double readGrade(int gradeNum)
{
    double grade;
    cout << "Enter Grade " << gradeNum <<" (From 0 to 100): ";
    if ( !(cin >> grade) )
    {
       // Clear the stream.
       cin.clear();

       // Discard everything up to the newline.
       cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

       // Call the function again.
       return readGrade(gradeNum);
    }

    return grade;
}

Then, replace the following lines in main

cout << "Enter Grade " << gradeNum <<" (From 0 to 100): ";

cin >> grade;

by a call to readGrade().

grade = readGrade(gradeNum);

1

solved C++ show me how stop this while infintie loop