character counting

Discussion in 'Mac Programming' started by jamesapp, May 22, 2008.

  1. jamesapp macrumors 6502a

    Mar 7, 2008
    i am working on a c programming book.

    The C Programming Language by
    Brian W. Kernighan and Dennis M. Ritchie

    there is a program for counting characters.
    i called the program prog1.5.2.c i will include it here:

    #include <stdio.h>
    /* count characters in input; 1st version */
      long nc;
      nc = 0;
      while (getchar() != EOF)
      printf("%ld\n", nc);
    the book calls it a character counting program.
    the program compiled without any errors, but when i went to run it it didn't seem to do anything but return a blank line.
    does anyone no what went wrong?

    there is also another way to write the above program using a for loop instead of while. i will list it here i called the c source file program prog1.5.2a.c

    #include <stdio.h>
    /* count characters in input; 2nd version */
      double nc;
      for (nc = 0; getchar() != EOF; ++nc)
      printf("%.0f\n", nc);
    again the program compiled but didn't seem to count characters.
    any help would be appreciated.
  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    The setup here is a bit weird, but it works. You need to get a file to stdin, or type EOF to get it to finish.

    For example, i called the code charc.c. I pasted the second example, compiled it as:
    gcc -o charc charc.c

    Then ran it as:
    ./charc < charc.c

    This takes the source file and uses it as the input to stdin. Since the file was sent to stdin, there is an EOF character sent to stdin at the end of the file.

    My output was 162.


    P.S. if you want to type it, it worked for me by running:
    Then typing:

    So the literal keys i pressed were:
    <enter key>
    <hold ctrl key, press d>

    ctrl-d will send the EOF
  3. jamesapp thread starter macrumors 6502a

    Mar 7, 2008
    i didn't know that cntrl d was EOF. i had been using cntrl c.
    i ran the program again and typed in abcd, then enter, and then cntrld
    i got 5D as output
    do you know what the D in 5D stands for?
    is this 4 letters (abcd) and an EOF character?
    i also tried ./charc < charc.c when i ran the program in terminal i got
    162 as output, is this the number of characters in the source file?
    does the program count spaces?
  4. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    The D looks like it was just displaying the ctrl+D for some reason, not sure on that.

    However, the 5 is a b c d and the newline.

    The program counts every character (space, newlines, tabs, etc.) except for the EOF.

    ctrl+C sends a signal to the program to die, so that will terminate it without the program finishing properly.


Share This Page