-1

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

Alllw7sh
  • 13
  • 3

2 Answers2

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
  • 1
    Slight 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