Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

320
Visualizações
why 'scanf' & 'getchar' adds newline to the input?

I'm trying to test this simple look up table, but can't understand why both scanf and getchar add the newline character ('\n') to the input:

const int arr[10] = {1,0,5,7,6,4,8,2,9,3};
char digit;

printf("enter digits please\n");
digit = getchar();
while ((digit>='0') && (digit<='9'))
{
    printf("%d --> %d\n",digit,arr[digit-'0']);
    digit = getchar();
}
printf("bye bye!");

when runnnig this code, both with printf or getchar() the while loop executes just once, since the newline char ('\n') is also stored in the char variable digit, & I can't figure out why.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

When you press the Enter key, it adds a newline to the input. If you want to skip that, you need to skip that. One easy way is by using scanf with a space in the format string, which skips all whitespace. Use:

scanf(" %c", &digit);

instead of digit = getchar(); in the two places you do that.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda