简体   繁体   中英

How to stop infinite looping the output?

I have code with a function that returns the biggest digit from a number. The requirement is to enter numbers until something that is not a number is entered. When something that isn't a number is entered, the program is supposed to stop, but in my case it just starts an infinite loop that prints the last result that the function returned. Here is the code:

#include <stdio.h>
int maxDigit(int n){
    int temp = n, maxDig = 0;
    while(temp){
        int digit = temp % 10;
        if(digit > maxDig){
            maxDig = digit;
        }
        temp /= 10;
    }
    return maxDig;
}
int main()
{
    int n = 1, broj;
    while(n){
    if(scanf("%d", &broj)); 
    printf("%d\n", maxDigit(broj)); 
    }
    return 0;
}

What might be the problem?

You can look at the return value of scanf to see if you read a valid integer, and you can use break to terminate your loop. The n variable in your main function just had a constant value so I got rid of it, and cleaned up the function in a few other ways. Here is my resulting code:

...
int main() {
  while (1) {
    int input;
    if (scanf("%d", &input) != 1) { break; }
    printf("%d\n", maxDigit(input)); 
  }
}

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