Deleting extra characters using scanf

0

Hello, friends!

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

The problem is that since data such as CNPJ and UF have specific numbers of characters to insert (14 and 2), I must put in the scanf for the strings to receive specific values of 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 carries the extra character for the next data, compromising all the following information. How do I prevent this from happening? Here is the passage I am referring 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 );
    
asked by anonymous 24.06.2014 / 02:31

2 answers

2

A very simple solution is to consume the end of the line after each reading. Remove% with% from your% with%. Then after each reading, whether successful or not, execute a %*[;\r\n] 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 by reading the entire line and then processing with scanf , breaking the semicolons. So you will not have to deal with the format string of fgets .

    
24.06.2014 / 03:03
1

Uses the return of scanf()

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