简体   繁体   中英

Can someone explain a c++ while loop?

So, I'm trying to create a program that has a never ending while loop unless the user pressing a certain key to exit. Now I'm pretty sure that I need to use a while loop but I'm not 100% sure how it works. I've been trying to add error messages to. The user is suppose to enter a numbered grade and it calculates the gpa but I need to validate the user input to make sure it is numeric and between 0 and 100 but after I put the error message in the loop it just is never ending (literally it shows the message down the page over and over without me touching anything) could someone explain?

int main()
{
    int grade;      // input
    char y;        //determines what letter to press to exit
    bool validGrade = true; //determines if grade is valid

    cout << "Enter percentage grades to convert to grade points. Press [y] to exit.";
    cin >> y;

    while(validGrade)
    {
        cout << "Percentage Grade: ";
        cin >> grade;

        if (!validGrade)
        {
            cout << "* Invalid input. Please try again and enter a numeric value.";
        }
    }
}

this is my code^

A C++ while loop,

while (condition) statement

Will repeatedly evaluate statement while condition evaluates to true .

A common issue that results in infinite loops is creating a program that never modifies condition such that it becomes false . For example, in your program, the condition is validGrade , which you've initialized to true . Do you ever modify validGrade ? If not, the condition will remain true forever, and thus loop forever.

You mentioned performing checks on grade , but it seems like you haven't implemented them yet. Think about how you could modify the condition variable to ensure that the loop terminates eventually.

I'd also encourage you to read some tutorials to gain a better understanding of while loops. Here's one to start you off.

Your while loop condition has been initialized to true . So it is supposed to run indefinitely. Based on your question, I think what you're trying to do is to check input stream:

int main() { 

int grade; // input 
char y; //determines what letter to press to exit 
bool validGrade = true; //determines if grade is valid

 cout << "Enter percentage grades to convert to grade points. Press [y] to exit."; 
cin >> y; 

while(cin >> grade) { 

cout << "Percentage Grade: "; 

if (!validGrade) { 

cout << "* Invalid input. Please try again and enter a numeric value."; 

} } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM