Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!