Type of char data needs space after quotation marks in the scanf

Asked

Viewed 118 times

2

#include <stdio.h>
#include <stdlib.h>

void main(){

  char elevador;
  int cod=0, a=0, b=0, c=0;


  while(cod == 0){
    printf("\nElevador utilizado (a/b/c)? ");
    scanf("%c", &elevador);

    switch(elevador){
      case 'a':
        a++;
        break;
      case 'b':
        b++;
        break;
      case 'c':
        c++;
        break;
      default:
        printf("opcao inválida!");
    }
  }
}

Why when I use the data type char and use the scanf() I need to make room after the first quotation marks?

In this way:

scanf(" %c", &lift); << Space after "_%c"

Because if you do not use my program as code at the beginning will work in an "abnormal" way you can test, it will run this way:

execução

1 answer

3


Because the scanf() treats the input with a line break at the end and this can cause problems of buffer. This space indicates that there will be a substitution of the line break that is spurious there. Usually only gives problem when there is read repetition where the line break ends up getting to the next entry.

Related.

  • Thanks again. The other topic helps me understand better. .

Browser other questions tagged

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