-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

6
  • Does this answer your question? How can I get an int from stdio in C? Commented Dec 12, 2019 at 22:46
  • 3
    You could read the input string and check that it only has digits before converting to an integer. Commented Dec 12, 2019 at 22:46
  • I believe you are looking for this: stackoverflow.com/questions/6280055/… Commented Dec 12, 2019 at 22:47
  • 1
    What do you want to happen if he does enter decimal points? Commented Dec 12, 2019 at 22:59
  • It depends greatly on how you are reading/parsing the input. Show some code! Commented Dec 13, 2019 at 0:22

2 Answers 2

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Slight simplification idea: "%d%n" --> "%d %n", then (str[index] != 0 && !isspace(str[index])) --> (str[index] != 0). Let sscanf() consume trailing white-spaces.
@chux-ReinstateMonica that's a good improvement. I was aware that the input 12 34 56 would be accepted - updated.
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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.