Validate user entered only number - C

0

I have a declared string as follows:

char    cpf[12];

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

I captured the value entered by the user like this:

gets(cpf);

Then I call a function that traverses this array "cpf", character by character, doing cast to convert string to int, to identify the presence of a non int.

The call looks 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 like this:

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

As far as I understand, it's missing casting somewhere. Could you help me identify?

    
asked by anonymous 08.11.2017 / 02:22

1 answer

3

There are several points that need attention:

Attribution vs Comparison

The first one was identified by the compiler. You only put = inside if , so you're making an assignment, not a comparison. Correction: use ==

Check if all digits are

The other compiler did not point: just return 0 at the end of the function. If you return early on, it will give a false positive to 123oliveira4 . It is also worth remembering that you must type the parameter. It's that you do not have to go to strlen , just stop before. You can do this tie better, but I will not get into the details now.

Oh, and you do not need to interact with stdin if you do not read from it in this function. Without fflush unnecessary.

You also do not need this "forced conversion" integer. Asking 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;
}

Do not read with gets

Use fgets(cpf, 11, stdin)

    
08.11.2017 / 02:32