I have an error in scanf

1

I have to read N lines with one of the following 3 formats:

    P k ": the letter P followed by k where k is an integer; A : the letter A followed by k being an integer;

  • " Q ": the letter Q .

As I do not know if the person goes by P / A or Q first I just have to read a letter.

If the letter is Q, I make the code for the letter. If it is P / A I still have to read an integer and then make the respective P / A code and its number.

My problem is that I make scanf for the first letter in this way at least:

for(idx = 0; idx < N ; idx++)
scanf("%c",&opc);

Within for I have some more code. The problem is this. The first time it goes well. The second time it arrives at scanf of char the compiler automatically puts the ASCII code character 10 representing the line break.

This happens because scanf does not clear the ENTERs buffer so I did this:

for(idx = 0; idx < N ; idx++)
scanf("%c\n",&opc);*

I've added \n to scanf to it to some extent consume line break.

In this way I get another error that is: (example) if the first input is Q for example it asks me for Q to read it only once.

So I put a Q and nothing happens. I put the second there and it advances and follows normally.

    
asked by anonymous 09.04.2016 / 03:27

1 answer

1

The "%c" converter (unlike many other scanf() converters) does not ignore blank spaces. If the input has spaces (or ENTERs or TABs) these spaces will be assigned to the specified variable.

To ignore blank spaces, add a space in the format string:

if (scanf(" %c", &x) != 1) /* error */;
//         ^ ignora zero ou mais espacos em branco (ou ENTERs, TABs)

Putting the space blank after the converter has a very amazing effect for those who are not waiting

Suppose the code was as follows and the user types "Q [ENTER] [ENTER] [ENTER] 42 [ENTER]"

scanf("%c ");

The% wrapper "catches" the 'Q' and scanf () jumps to the blank space. This part "picks up" the first [ENTER], the second [ENTER], third p [ENTER] and stops only when it reaches "4". The "4" (and the "2" and [ENTER]) are in the buffer waiting for the next read instruction.

    
09.04.2016 / 10:46