0

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 a a -1 -1 -1 Why?

yuxuan
  • 417
  • 5
  • 16
  • 2
    This has to be a duplicate. – David Hammen Jan 30 '16 at 18:09
  • 1
    Linked: http://stackoverflow.com/questions/13031414/cin-loop-never-terminating . In particular, see the answer by Dietmar Kühl. I am not voting to close (for now), because if I did so, this question would be closed instantaneously. – David Hammen Jan 30 '16 at 18:13
  • 1
    `a` is not a valid representation of an integer, so extraction fails and `std::cin` enters a permanent failure state - further extractions also fail. But yeah, this is a duplicate, so look around for solutions. – Archimaredes Jan 30 '16 at 18:14

2 Answers2

2

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.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
1

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;
}
Paul Evans
  • 27,315
  • 3
  • 37
  • 54