Home > OS >  How to stop infinite looping the output?
How to stop infinite looping the output?

Time:01-08

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?

CodePudding user response:

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)); 
  }
}
  •  Tags:  
  • Related