0

I'm trying to write a function that checks input. I've seen some code like this but they didn't get the input until it got int. My function should get the input and check it. It should be used like "check(input)"; Here is something I tried and failed;

char n[10];

fgets(n, sizeof(n), stdin);
strtol(n, NULL, 10);

int i;
for (i = 0; i < strlen(n); i++) {
    while(! isdigit(n[i])) {
        if (n[i] != '.') {
            printf("Wrong! Enter again:");
            fgets(n, sizeof(n), stdin);
        }
    }
}

return buf;
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • 1
    Similar; https://stackoverflow.com/q/67143601/634919 – Nate Eldredge Apr 18 '21 at 18:21
  • See full validation in answer to [Read integers from a specific line from a file in c](https://stackoverflow.com/a/53800654/3422102) involving `strtol()`, but will be virtually identical. See also [get numbers value from a char array in C](https://stackoverflow.com/a/56162952/3422102) – David C. Rankin Apr 18 '21 at 19:44

2 Answers2

1

If you simply want to make sure that the input is a valid floating point number, strtod is your friend:

#include <stdlib.h>
#include <errno.h>

double check(const char input[])
{
    char* p;
    errno = 0;
    double n = strtod(input, &p);
    if (errno == ERANGE)
        ;//range error, the input doesn't fit on the type
    if (p == input)
        ;//fail, not a number
    return n;
}

There are some cases which pass through this test, but you may not want to, such as nan, or hexadecimal notation, so you need to take care of that.

DarkAtom
  • 2,589
  • 1
  • 11
  • 27
0

Thank you so much! I added a little bit to your solution. Please let me know if there is anything unnecessary or useless.

double check(const char input[]) {

char *p;
errno = 0;
double n = strtod(input, &p);

    if (errno == ERANGE) {
        //range error, the input doesn't fit on the type
        return 0;
    } else if (p == input) {
        //fail, not a number
        return 0;
    } else if (*p && *p != '\n' && *p != '.' && *p != ',') {
        // *endptr is neither end of string nor newline,
        // so we didn't convert the *whole* input
        return 0;
    }
return n;

}