简体   繁体   中英

char input makes the loop not stop in C++

The C++ program is as follows

#include <iostream>

using namespace std;

int main(void) {
    /* temporary storage for the incoming numbers */
    int number;

    /* we will store the currently greatest number here */
    int max = -100000;

    /* get the first value */
    cin >> number;

    /* if the number is not equal to -1 we will continue */
    while(number != -1) {

        /* is the number greater than max? */
        if(number > max)

            /* yes – update max */
            max = number;

        /* get next numbet */
        cin >> number;
    }

    /* print the largest number */
    cout << "The largest number is " << max << endl;

    /* finish the program successfully */
    return 0;
} 

If I enter some number such as 69 10 -1 . It will work. But when I enter some char, even I enter -1 , it didn't stop. For example aa -1 -1 -1 Why?

You need to check the stream state after each read.

The letter a is not a proper decimal digit, so the input fails. When the input fails, it sets a failure bit, which causes all subsequent inputs to fail or not occur.

Always check the input status after reading a variable.

The recovery is to clear the status if you want to continue.

Because you want the input statement as your while condition, something like:

while (cin >> number) {

    if(number == -1)
        break;

    if (number > max)
        /* yes – update max */
        max = number;
}

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