Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

scanf

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.

like image 732
niko Avatar asked Aug 20 '13 15:08

niko


2 Answers

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?

like image 200
Jonathan Leffler Avatar answered Oct 14 '22 06:10

Jonathan Leffler


You'll have to read it as a double and then check if it is an integer. The best way to check if it is an integer is to use modf, which returns the decimal portion of the double. If there is one you have an error:

double d;
scanf("%lf", &d);

double temp;
if(modf(d, &temp)){
  // Handle error for invalid input
}

int a = (int)temp;

This will allow integers or floating point numbers with only 0s after the decimal point such as 54.00000. If you want to consider that as invalid as well, you are better off reading character by character and verifying that each character is between 0 and 9 (ascii 48 to 57).

like image 28
Paul Avatar answered Oct 14 '22 07:10

Paul