-2

I am just starting out learning c. Downloaded xcode to my mac and bought The c Programming Language by K&R. I am now at the character counting section and cannot understand the output the program gives me. Program is...

#include <stdio.h>
main()
{
    long nc;
    nc = 0;
    while (getchar() !=EOF)
        ++nc;
    printf("%ld\n", nc);
}

I've learned from these pages that I need to hit ctrl+d twice to send an EOF character to the program and that works ok. However, the answer it gives me is 140,734,799,804,376 (the commas are mine) plus the number of characters in the string. Where does this huge number come from? Why doesn't the program just return 4 for "help" instead of 140734799804380?

Hendrik
  • 301
  • 1
  • 3
  • 7
  • 2
    try adding semi-colons to make code example compilable! – Mitch Wheat Nov 17 '15 at 05:37
  • Possible duplicate of [Why do I need to press CTRL+D twice to break out of \`while ((c=getchar())!=EOF)\` in Ubuntu 14.10?](http://stackoverflow.com/questions/30137434/why-do-i-need-to-press-ctrld-twice-to-break-out-of-while-c-getchar-eof) – ameyCU Nov 17 '15 at 05:38
  • I can't reproduce your problem; how are you compiling and running the code? On the command line? –  Nov 17 '15 at 05:44
  • ctrl+r runs the program – Hendrik Nov 17 '15 at 05:47

1 Answers1

0
nc = 0 

and

++nc

Missing semicolon here, change to :

nc = 0;

++nc;

I tried the same code like this :

./test.exe
hello<CTRL+D>5
Akhil Thayyil
  • 9,263
  • 6
  • 34
  • 48