1

I am currently trying to learn C by using the K&R, but I am completely stumped by example 1.5.2. For some reason, after I press Ctrl-Z, instead of printing nc, it prints nc multiplied by 2. I don't know what could be causing this problem (I copied the code exactly how it is in the book). The compiler I am using is Visual Studio 2010. Here is the code:

#include <stdio.h>

main()
{

long nc;

nc = 0;
while (getchar() != EOF)
    ++nc;
printf("%1d\n", nc);


}
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Emryss
  • 13
  • 4

3 Answers3

2

Because enter is a keystroke.

If your input is:

1<enter>
1<enter>
1<enter>
^z

it would output:

6

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
1

Not sure why you get the behaviour you describe but that should be %ld not %1d

Tom
  • 43,583
  • 4
  • 41
  • 61
0

Could not reproduce your error. I added some debugging statements,

#include <stdio.h>

main() {
     int nc = 0, ch;

     while ((ch = getchar()) != EOF) {
          printf("%d\n", ch);
          ++nc;
     }
     printf("nc - %1d\n", nc);


}

And then tried it with gcc on Windows:

E:\temp>gcc eof.c

E:\temp>a
^Z
nc - 0

E:\temp>a
foo bar
102
111
111
32
98
97
114
10
^Z
nc - 8

And then with Visual Studio 2008:

E:\temp>cl eof.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

eof.c
Microsoft (R) Incremental Linker Version 9.00.30729.01
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:eof.exe
eof.obj

E:\temp>eof
^Z
nc - 0

E:\temp>eof
foo bar
102
111
111
32
98
97
114
10
^Z
nc - 8
Roshan Mathews
  • 5,788
  • 2
  • 26
  • 36
  • He was hitting `enter` after each letter he typed (resulting in `nc` being twice as large as he expected). See comments. – Brian Roach Sep 18 '11 at 06:45