Eliminating extra characters using scanf

Asked

Viewed 371 times

0

Hello, my friends!

I am creating a program that reads data separated by semicolons, the Czech and returns a list with possible errors. (example: the user enters CNPJ, social reason, UF as follows: 12345678901234;company x;SP). I am doing so because the next step is to take a file . txt ready with thousands of companies in this format and use it in the program.

The problem is that, as the data such as CNPJ and UF have specific numbers of characters to be inserted (14 and 2), I must put in the scanf for the strings to receive specific values from cnpj and UF. This I can do without problems, including the part of reading the data to the semicolon. What happens is that if the user types extra characters in CNPJ (15 characters, for example), the keyboard buffer loads the extra character for the next data, compromising all of the following information. How do I make this not happen? Below is the section I refer to:

scanf( "%14[^;];%40[^;];%8[^;];%2[^;\r\n]%*[;\r\n]",
          cnpj,
          razao_social,
          data_de_fundacao,
          uf );
          validaCNPJ(cnpj);
    if (validaCNPJ(cnpj) == 0){
        cnpjErr = cnpjErr + 1;
        }

    contador_linhas++;

    printf( "\n[%4d][%-14s][%-40s][%-8s][%-2s]",
            contador_linhas,
            cnpj,
            razao_social,
            data_de_fundacao,
            uf );
  • Have you ever taken a look at the fflush function?

2 answers

2

A fairly simple solution is to consume the end of the line after each read. Remove %*[;\r\n] of your scanf. Then after each reading, whether it is successful or not, run a fgets with a reasonable size buffer. It will read the whole line and position the next reading at the beginning of the next line.

I should warn, however, that a probably better way to do this would be to read the entire line and then process with strtok, breaking at the semicolons. So you won’t have to deal with the format string of the scanf.

1

Use the return of scanf()

if (scanf("%14[^;];%40[^;];%8[^;];%2[^;\r\n]%*[;\r\n]",
          cnpj,
          razao_social,
          data_de_fundacao,
          uf) != 4) /* erro */;

Browser other questions tagged

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