Mehmet Saglam
Mehmet Saglam

Reputation: 1

How can I check the input in C

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;

Upvotes: 0

Views: 63

Answers (2)

Mehmet Saglam
Mehmet Saglam

Reputation: 1

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;

}

Upvotes: 0

DarkAtom
DarkAtom

Reputation: 3161

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.

Upvotes: 1

Related Questions