Check data received by the user

Asked

Viewed 40 times

-2

How can I check if the user typed a die the way I’m hoping?

For example, I want him to type an integer value. How do I know if the value he typed was an integer and not a char or float, and if the input is not an integer, send an error message and continue asking for an integer?

I haven’t started writing the code yet.

  • 1

    The idea of the site is to give a guideline for what you are already doing and not exactly offer a ready-made solution. I suggest you see some tutorials on how to read inputs in C and do.

  • Can put a if to verify the type of data the person entered.

1 answer

0

Very simple:

int eh_inteiro(const char *c) {
    int i = c[0] == '-' || c[0] == '+';
    if (!c[i]) return 0;
    while (c[i]) {
        if (c[i] < '0' || c[i] > '9') return 0;
        i++;
    }
    return 1;
}

Here’s a test for her:

void testar(const char *c) {
    printf("%s: %s\n", c, eh_inteiro(c) ? "Sim" : "Não");
}

int main(void) {
    testar("123");
    testar("+123");
    testar("-123");
    testar("1");
    testar("0");
    testar("9");
    testar("999999");
    testar("-5");
    testar("-");
    testar("+");
    testar("");
    testar("banana");
    testar("123a");
    testar("12a3");
    testar(" ");
    testar(" 12");
    testar("12 ");
    testar("1 2");
}

Here’s the way out:

123: Sim
+123: Sim
-123: Sim
1: Sim
0: Sim
9: Sim
999999: Sim
-5: Sim
-: Não
+: Não
: Não
banana: Não
123a: Não
12a3: Não
 : Não
 12: Não
12 : Não
1 2: Não

See here working on ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.