Reputation: 13
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);
}
Upvotes: 1
Views: 407
Reputation: 76918
Because enter
is a keystroke.
If your input is:
1<enter>
1<enter>
1<enter>
^z
it would output:
6
Upvotes: 2
Reputation: 5898
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
Upvotes: 0
Reputation: 44881
Not sure why you get the behaviour you describe but that should be %ld not %1d
Upvotes: 1