0
#include <stdio.h>

/* count characters in input; 2nd version */
main()
{
    double nc;

    for (nc = 0; getchar() != EOF; ++nc)
        ;

    printf("%.0f\n", nc);
}

When I compile and run the program and type in a character (example: abcd), hit enter, then hit the escape character CTRL+Z, it says 5. Is that because of the "hidden" newline character or does it count the EOF command? Because when I type the EOF command alone it stays as 0.

xyz
  • 393
  • 2
  • 12
  • 1
    I think you answered your own question, given that you get 0 when you do only EOF. As a test, why not enter 3 lines of text then an EOF just to be sure? – lurker Nov 22 '14 at 01:27
  • Alright, I see now. I just want to be 100% sure of all of the programs/exercises before I move on. Thanks. – xyz Nov 22 '14 at 01:31
  • Is there any particular reason you count in `double`? – EOF Nov 22 '14 at 01:36
  • That was just used as an example in the K&R C book. – xyz Nov 22 '14 at 01:43
  • Please make sure to *copy* code, not type it in. Proof: `gechar` – Jongware Nov 22 '14 at 01:44
  • Oh, my apologies. I actually did copy and it seems it was wrong in the listed example. I'll be sure to check again next time. – xyz Nov 22 '14 at 01:46
  • What OS are you using System/360 or Windows? – Ryan Nov 22 '14 at 02:13

1 Answers1

1

Yes.

getchar waits for you to enter "something"; and Enter is 'something' (that is, it has a defined character value; other keys, Shift for example, may not).

By that same token, the key combo Ctrl+Z would be "something" as well -- the value 26 on most systems -- but the standard input/output library you are using treats this particular code as a special command: EOF. On my OS, Mac OSX, that would be Ctrl+D (for reasons unknown to me, other than "historically, Ctrl+D is used to signal EOF on Unix-like systems").

The 'newline character' is by no means "hidden" or "invisible", it's just another number that gets read and stored into a variable or string if you instruct it to do so. The reason you cannot see it is because putchar and other text printing functions do something else than "display the associated character": it moves the cursor to the next line. That also is part of the standard functionality, and a good thing it is too. After all you wouldn't want to press Space to "move to the next line". (In fact it's such a common function of this code that most fonts don't even bother to have a displayable item for it.)

See also What does getchar() exactly do? for more background information.

Community
  • 1
  • 1
Jongware
  • 22,200
  • 8
  • 54
  • 100