I want to receive an integer from the user, how can I know if he enters whole numbers without using decimal points like 1 2 3 and not 1.4 or 2.0 or 3.0
Asked
Active
Viewed 81 times
-1
-
Does this answer your question? [How can I get an int from stdio in C?](https://stackoverflow.com/questions/5087062/how-can-i-get-an-int-from-stdio-in-c) – Iguananaut Dec 12 '19 at 22:46
-
3You could read the input string and check that it only has digits before converting to an integer. – lurker Dec 12 '19 at 22:46
-
I believe you are looking for this: https://stackoverflow.com/questions/6280055/how-do-i-check-if-a-variable-is-of-a-certain-type-compare-two-types-in-c – DevKyle Dec 12 '19 at 22:47
-
1What do you want to happen if he does enter decimal points? – M.M Dec 12 '19 at 22:59
-
It depends greatly on how you are reading/parsing the input. Show some code! – William Pursell Dec 13 '19 at 00:22
-
How larger an integer is acceptable? – chux - Reinstate Monica Dec 13 '19 at 02:45
2 Answers
1
By testing every step of the way, you can ensure that only an integer number was entered.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
char str[100];
int num, index;
if(fgets(str, sizeof str, stdin) == NULL) {
// returns NULL if failed
printf("Bad string input\n");
}
else if(sscanf(str, "%d %n", &num, &index) != 1) {
// returns the number of converted items
// and sets index to the number of characters scanned
printf("Bad sscanf result\n");
}
else if(str[index] != 0) {
// checks that the string now ends (trailing whitespace was removed)
printf("Not an integer input\n");
}
else {
// success
printf("Number is %d\n", num);
}
}

Weather Vane
- 33,872
- 7
- 36
- 56
-
1Slight simplification idea: `"%d%n"` --> `"%d %n"`, then `(str[index] != 0 && !isspace(str[index]))` --> `(str[index] != 0)`. Let `sscanf()` consume trailing white-spaces. – chux - Reinstate Monica Dec 13 '19 at 02:43
-
@chux-ReinstateMonica that's a good improvement. I was aware that the input `12 34 56` would be accepted - updated. – Weather Vane Dec 13 '19 at 06:51
0
You could read the input as a string and then scan the string for a dot.
#include <string.h>
#include <stdio.h>
int main (void) {
int i;
float f;
char input[256];
char dummy[256];
fgets(input, 256, stdin);
if(strchr(input, '.') != NULL) {
if(sscanf(input, "%f%s", &f, dummy) == 1) {
printf("%f is a float\n", f);
} else {
//error case
}
} else {
if(sscanf(input, "%d%s", &i, dummy) == 1) {
printf("%d is an integer\n", i);
} else {
// error case
}
}
return 0;
}

hko
- 548
- 2
- 19