Ricardo Vieira
Ricardo Vieira

Reputation: 13

How do i know if the input is an character or a float number with scanf?

I'm trying to make a simple calculator without any errors but in addition, per example, if I input an "a" the program has an unexpected output. Basically my question is what can I do for the program to show up a warning when I input a character. Maybe the scanf return any useful value?

Upvotes: 0

Views: 105

Answers (1)

snaipeberry
snaipeberry

Reputation: 1069

You can simply use the flags scanf is providing to scan integers.

int main()
{
    float nb;

    if (scanf("%f", &v) == 1) {
        printf("Is float !\n");
    } else {
        printf("Not a float !\n");
    }
    return 0;
}

scanf returns the number of flags successfuly reads, so if this number is different than 1 (in this example), that means scanf couldn't convert your input in float.

In the case of an addition:

int main()
{
    float a;
    float b;

    if (scanf("%f +%f", &a, &b) == 2) {
        printf("Result is %f\n", a + b);
    } else {
        printf("Error !\n");
        return 1;
    }
    return 0;
}

This works but you have to write the exact scanf string. I suggest you to read the input line as a string instead, and then parse it using strtol or other functions.

Upvotes: 1

Related Questions