I have a bug in the scanf

Asked

Viewed 309 times

1

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

  • "P k": the letter P followed by k being k an integer number;
  • "A k": the letter To followed by k being k an integer number;
  • "Q": the letter Q.

Since I don’t know if the person goes by P/A or Q first I just have to read a letter.

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

My problem is I do scanf for the first letter this way more at least:

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

Within the for I have some more code. The problem is this. The first time goes well. The second time it comes to scanf of char compiler automatically puts ASCII code Character 10 representative of line break.

This is because the scanf does not clear the Enters buffer so I did this:

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

I added a \n us scanf for him to somehow consume the line break.

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

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

  • puts a \n before the %c. scanf("\n%c", &opc);

  • The best (safer, more controllable) option to get user input is with the fgets() possibly followed by removing ENTER and/or sscanf() to isolate parts of the input.

1 answer

1

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

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

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

Leaving space blank after the converter has a pretty amazing effect for someone who isn’t waiting

Suppose the code was the following and the user type "Q [ENTER] [ENTER] [ENTER] 42 [ENTER]"

scanf("%c ");

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

Browser other questions tagged

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