'How to check user's input data type in C? [duplicate]
#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.
Solution 1:[1]
Verify that the return value of scanf("%i", &userNum) is 1.
For example:
if (scanf("%i", &userNum) != 1) {
// print some error and return from the function
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bbbbbbbbb |
