2

I'm reading/practicing with this book about C language: "C Programming - A Modern Approach 2" and I stumbled upon this piece of code whose explanation is odd to me:

Since scanf doesn't normally skip white spaces, it's easy to detect the end of an input line: check to see if the character just read is the new-line character. For example, the following loop will read and ignore all remaining characters in the current input line:

do {
    scanf("%c", &ch);
} while (ch != '\n');

When scanf is called the next time, it will read the first character on the next input line.

I understand the functioning of the code (it exits the loop when it detects enter or '\n') but not the lesson(?).

What is the purpose of this, since to store the input from the user into &ch you HAVE to press the enter key (quitting the loop)?

Also what does "the following loop will read and ignore all remaining characters in the current input line" mean actually?

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
dotthor
  • 68
  • 10

1 Answers1

2

...What is the purpose of this...

For context in understanding what this code snippet can be used for, take a look at this link discussing stdio buffering. In simplest logical terms, this technique consumes content placed in stdin until the newline character is seen. (From a user hitting the <enter> key.) This is evidently the lesson.
This effectively clears the stdin buffer of content, also described in this more robust example.

Also what does

"the following loop will read and ignore all remaining characters in the current input line"

mean actually?

do {
    scanf("%c", &ch);
} while (ch != '\n');

It means that if the new char just read by scanf is not equal to the newline character, defined as \n, it will continue to overwrite c with the next read. Once ch does equal \n, the loop will exit.

ryyker
  • 22,849
  • 3
  • 43
  • 87
  • My impression from the wording of the question is the OP does not know about buffering of input. – Richard Chambers Sep 18 '19 at 12:51
  • @Richard - Good point. I've added a few lines, and links to touch on that. Thanks – ryyker Sep 18 '19 at 13:04
  • As @RichardChambers pointed out i'm pretty new to programming and I only know the basics (if I do) of _C_ . So the first part is out of my hands for now. Nonetheless thanks to the second part of your explanation I got the point that I was missing. – dotthor Sep 18 '19 at 14:42