-5

I want to take an float input but if the user gives a character input it will show invalid input, I didn't found a specific answer on the net. How is it done?

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
Jimut
  • 195
  • 3
  • 13

2 Answers2

2

Consider the following code fragment:

int num;
float val;

num = scanf("%f", &val);
if(num != 1)
{
    printf("You didn't enter a float!\n");
}

scanf returns the number of items that it successfully scans. In your case, you're trying to scan one item, a float. If the user doesn't enter a float, scanf will return 0.

Note: If scanf fails, whatever garbage data the user entered will still be in the stdin stream. You'll have to manually flush it. Here's one such way:

while(((ch = getchar()) != '\n') && (ch != EOF))
    continue;

Warning: Don't use fflush on stdin.

Edit

Even if scanf doesn't fail, you may still have garbage in the stdin buffer. For example, if the user enters:

123xyz

123 will be assigned to the float, and everything after x will stay in the stdin stream.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
2

While scanf is safe to parse a double, many compilers have deprecated its use (for good reason) becuase it is unsafe when parsing a string. Additionally, should the parse fail, you will be left with the remains in the input buffer and you will have to flush it yourself.

For these reasons, prefer a function like fgets, which checks the length of its supplied buffer, and then a function like strtod or sscanf to make the conversion.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char buf[64];

    /* read */
    if (fgets(buf, sizeof buf, stdin)) {
        /* convert */
        char *err;
        double d = strtod(buf, &err);
        if (*err) {
            puts("entry invalid");
        } else {
            printf("you entered %lf", d);
        }
    }

    return 0;
}
Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • input like 123xyz is valid? – SHR Aug 09 '14 at 21:06
  • 2
    Everyone is suggesting `scanf` because `scanf` is not “inherently” unsafe to parse a `double`. – Pascal Cuoq Aug 09 '14 at 21:37
  • 2
    Well, okay, 50% of `scanf`-suggesting answers are suggesting `scanf` because `scanf` is not inherently unsafe. – Pascal Cuoq Aug 09 '14 at 21:41
  • @PascalCuoq: Yeah, fair enough re: parsing a number, but I still wouldn't use/teach it. I removed that bit. – Ed S. Aug 10 '14 at 00:35
  • `if (fgets(buf, sizeof buf, stdin)) { double d = strtod(buf, &err); if (*err) {` is a problem, but on the right track. `fgets()` will most often get a string ending in `"\n\0"` and then `*err` will have the `'\n'` in it. Maybe add `while (isspace(*err)) err++` before the `if()`? – chux - Reinstate Monica Aug 16 '14 at 03:37