0
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void main()
{
int userNum;
int count=0;

printf("Please enter a whole number: ");
scanf("%i", &userNum);

while (userNum != 999)
{
    if (userNum > 0)
    {
        printf("Factors: ");
        for (count = 1; count <= userNum; count++)
        {
            if ((userNum % count) == 0)
            {
                printf("%i ", count);
            }
        }
    }
    else
    {
        printf("You input a negative number");
    }
    printf("\nPlease enter a whole number: ");
    scanf("%i", &userNum);
}
printf("\n");
system("pause");

}

Hey guys, that is my code for finding factors of a number given by the user. I have a problem: the program will run into an infinite loop if the user inputs a character or a double number. So, I want to ask how to solve that problem. I really like coding. Please help. Thank you so much.

  • Please tell us what your program should do if the user enters say `afd` instead of `123`. – Jabberwocky Feb 17 '22 at 16:36
  • 1
    `scanf` does not consume any data that does not match the conversion specifier. Probably the easiest thing to do is to check the value returned by scanf. If it is not 1 (to indicate that it matched on specifier and thus consumed some data), you should probably just read and discard data up until the next newline. – William Pursell Feb 17 '22 at 16:39

0 Answers0