How to ignore floating number in scanf("%d")?

c, scanf

Solution

Since the start of a floating point number with any digits before the decimal point looks like an integer, there is no way to detect this with `%d` alone.

You might consider reading the whole line with `fgets()` and then analyzing with `sscanf()`:

int a;
int n;
char line[4096];
if (fgets(line, sizeof(line), stdin) != 0 && sscanf(line, "%d%n", &a, &n) == 1)
   ...analyze the character at line[n] for validity...

(And yes, I did mean to compare with 1; the `%n` conversion specifications are not counted in the return value from `sscanf()` et al.)

One thing that `scanf()` does which this code does not do is to skip blank lines before the number is entered. If that matters, you have to code a loop to read up to the (non-empty) line, and then parse the non-empty line. You also need to decide how much trailing junk (if any) on the line is tolerated. Are blanks allowed? Tabs? Alpha characters? Punctuation?

Problem

If user enters floating number for an integer variable I want to print invalid input. is that possible? ``` int a; scanf("%d",&a); // if user enters 4.35 print invalid input ``` I have tried for characters like this ``` if(scanf("%d",&a)==1); else printf("invalid input"); ``` But how to do for floating numbers. If user enters `4.35` it truncates to `4` but I want invalid input.

Original source

Related problems