Validate user typed only number - C

Asked

Viewed 952 times

0

I have a string declared as follows:

char    cpf[12];

I want to validate that the user typed only numbers when he typed ENTER.

I captured the value typed by the user like this:

gets(cpf);

Soon after, I call a function that traverses this array "Cpf", character by character, casting to convert string to int, in order to identify the presence of a non int.

The call went like this:

        if ((valida_cnh_cpf(cpf)) = 1) {
            printf("Erro, informe somente números para CPF\n");
            system("pause");
            system("cls");
            menu();
        } 

And the function was declared so:

int valida_cnh_cpf(cpf_cnh) {
    fflush(stdin);
    int cpf_cnh_convertido[11];
    int i;

    for (i = 0; i <= strlen(cpf_cnh); i++) {
        cpf_cnh_convertido[i] = (int) cpf_cnh[i];
        if (isdigit(cpf_cnh_convertido[i])) {
            return 0;
        } else {
            i = strlen(cpf_cnh) + 1;
            return 1;
        }
    }
}

The problem is soon in the build. I get the following error pointing to the for line:

[Warning] Passing argument 1 of 'strlen' makes Pointer from integer without a cast

From what I understand, I have to cast somewhere. Could you help me identify?

1 answer

3


There are several points that need attention:

Attribution vs Comparison

The first one was identified by the compiler. You put only one = within the if, so you’re doing an assignment, not a comparison. Fix: use ==

Check that they are all digits

The other compiler did not point: only return 0 at the end of the function. If you return right at the beginning, it will give a false positive for 123oliveira4. Also worth remembering that you must type the parameter. Is that you do not need to go up strlen, just stop before. There is a way to make this loop better, but I won’t go into the details now.

Ah, and you don’t need to interact with stdin if you are not reading from it in this function. Without fflush unnecessary.

You also don’t need this whole pair "forced conversion". Ask for isdigit is enough.

Solution:

int valida_cnh_cpf(char *cpf_cnh) {
    int i;

    for (i = 0; i < strlen(cpf_cnh); i++) {
        if (!isdigit(cpf_cnh[i])) {
            return 1;
        }
    }
    return 0;
}

Don’t read with gets

Use fgets(cpf, 11, stdin)

  • 1

    Jefferson, thank you very much.

  • @Angelo, in need, just keep asking good questions that good answers will sprout from the ground like weeds =)

Browser other questions tagged

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