0

I was wondering what's happening in this code from K&R C:

#include <stdio.h>

int main() {
    double nc;

    for (nc = 0; getchar(); ++nc) {
        ;
    }
    printf("%.0f\n", nc);
}

When I run the code (OS X El Capitan), the for loop doesn't finish and I can't get to the printf statement.

Jon
  • 150
  • 1
  • 3
  • 15
egarro
  • 141
  • 9

4 Answers4

4

The getchar() returns the obtained character on success or EOF on failure. Reference here.

Try this

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

Note that, Enter doesn't means EOF, it means newline or '\n'.

Look at the header stdio.h, says,

#define EOF (-1)

Here you can see how to simulate an EOF.

Windows: Ctrl+Z
Unix :   Ctrl+D

So long story short, you can put any condition in the for loop, like

for (nc = 0; getchar() != '\n'; ++nc) { } // break the loop if enter pressed
for (nc = 0; getchar() != 'c'; ++nc) { } // break the loop if c pressed
.
.
.
Community
  • 1
  • 1
mazhar islam
  • 5,561
  • 3
  • 20
  • 41
1

getchar() waits on the input from stdin and even if you enter any character it would be read by getchar() but that doesn't make you get out of the loop.

So you need to add some condition on the return value of getchar() to gracefully exit the loop.

For Eg:

for(;getchar() != EOF;)
{
}

If you want to return on newline character then check should be getchar() != '\n'

PS: I have just shown how to check the return value , for me the exit condition is EOF it might vary for you.

Gopi
  • 19,784
  • 4
  • 24
  • 36
1

This loop

for (nc = 0; getchar(); ++nc) {
        ;

will iterate until getchar() returns 0. To achieve this without rewritting the program as others are suggesting you should for example in Windows press key combination Ctrl + @ and then press Enter. The value of key combination Ctrl + @ is equal to 0.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

If you revise your code to make it:

#include <stdio.h>

int main() {
    double nc;

    while (getchar() != EOF) {
        ++nc;
    }

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

Then if you run it in a terminal window and enter the following:

abcCtrl-D

you will get the output:

abc
3

(The Ctrl-D is the EOF character)

David
  • 14,047
  • 24
  • 80
  • 101
  • "The Ctrl-D is the EOF character" .. for Unix. Not for Windows. Why type twice? Why did you change the type of nc? – too honest for this site Jun 29 '15 at 15:22
  • Olaf - the questioner is using OS X, I assume in a terminal window, but I admit I might be wrong about that. – David Jun 29 '15 at 15:53
  • It is just if Windows-unsers read that; this might trigger another unecessary complaint. However, I removed the downvote, as my major concern was the changed type - I completely understand, actually; had to check myself first if that is actually allowed for float types. – too honest for this site Jun 29 '15 at 16:41