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
-
Does this answer your question? How can I get an int from stdio in C?Iguananaut– Iguananaut2019-12-12 22:46:30 +00:00Commented Dec 12, 2019 at 22:46
-
3You could read the input string and check that it only has digits before converting to an integer.lurker– lurker2019-12-12 22:46:34 +00:00Commented Dec 12, 2019 at 22:46
-
I believe you are looking for this: stackoverflow.com/questions/6280055/…DevKyle– DevKyle2019-12-12 22:47:29 +00:00Commented Dec 12, 2019 at 22:47
-
1What do you want to happen if he does enter decimal points?M.M– M.M2019-12-12 22:59:16 +00:00Commented Dec 12, 2019 at 22:59
-
It depends greatly on how you are reading/parsing the input. Show some code!William Pursell– William Pursell2019-12-13 00:22:04 +00:00Commented Dec 13, 2019 at 0:22
|
Show 1 more comment
2 Answers
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);
}
}
2 Comments
chux
Slight simplification idea:
"%d%n" --> "%d %n", then (str[index] != 0 && !isspace(str[index])) --> (str[index] != 0). Let sscanf() consume trailing white-spaces.Weather Vane
@chux-ReinstateMonica that's a good improvement. I was aware that the input
12 34 56 would be accepted - updated.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;
}