How to check if a code contains 3 letters and 4 numbers in this order?

0

I'm assigning the function return checks code to a flag. The idea is to make the flag trigger the loop if the code is incorrect

char *leValidaCodigoAviao(char *msg, char *msgErro){
    char *pNome=0, nome[MAX];
    strcpy(nome, "");
    int stringTam=0, flag=1, verificador=0;

    do{
        printf("%s", msg);
        fflush(stdin);
        scanf("%[^\n]s", nome);

        if(strlen(nome)==0){
            printf("%s", msgErro);
            flag=0;
        }else if(strlen(nome)<COD_ID || strlen(nome)>COD_ID){
            flag=0;

        }else{

            verificador = verificaCodigo(nome);
            printf("%d", verificador);
            flag = verificador;
        }


    }while(!flag);
    system("cls");
    getch();
    return pNome = nome;
}
int verificaCodigo(char nome[]){
    int i, flag=1;


    for(i=0;i<COD_ID;i++){
        if(i<3){
            if(!isalpha(nome[i])){
                flag=1;
                break;
            }
        }else{
            if(!isdigit(nome[i])){
                flag=1;
                break;
            }
        }
    }

    return flag;
}
    
asked by anonymous 12.11.2018 / 16:08

1 answer

1

Since your verificaCodigo function is written, it is easier to change the assignment you have in ifs to do what you want. So every time you see that a letter or a digit is not in the right place, it sets flag to 0 instead of 1 and ends for :

int verificaCodigo(char nome[]){
    int i, flag=1;

    for(i=0;i<COD_ID;i++){
        if(i<3){
            if(!isalpha(nome[i])){
                flag=0; //0 em vez de 1
                break;
            }
        }else{
            if(!isdigit(nome[i])){
                flag=0; //0 em vez de 1
                break;
            }
        }
    }

    return flag;
}

Tests:

printf("%d\n", verificaCodigo("ABC1234")); //1
printf("%d\n", verificaCodigo("1BC1234")); //0
printf("%d\n", verificaCodigo("AB11234")); //0
printf("%d\n", verificaCodigo("QQQ9999")); //1
printf("%d\n", verificaCodigo("123ABCD")); //0
printf("%d\n", verificaCodigo("abc1234")); //1
printf("%d\n", verificaCodigo("aBc9999")); //1
printf("%d\n", verificaCodigo("a0b1234")); //0

See it on Ideone

The way I had to start flag in 1 and put 1 inside if would not make sense because I was putting the value I already had, and did not put 0 in any situation .

    
12.11.2018 / 17:02