-1

This example is from "The C Programming Language" by Dennis Ritchie and Brian Kernighan. It is supposed to take in characters given by user input, and then when an EOF is stated (using my Mac, it is ctrl-D), it ends the program and shows the amount of characters inputted. Instead it doubles the actual value of the amount of characters. Am I missing something? Thank you.

#include <stdio.h>

main()
{
    long nc;

    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%1d\n", nc);
}
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
Manolo Ribera
  • 103
  • 1
  • 4
  • 8

1 Answers1

5

It is not doubling the value, for example if you type :

a
b
c
Ctrl+D

you will see 6 cause there is a line break after each character like:

a\n
b\n
c\n
Ctrl+D

\n is considered as a character (if am not wrong, in mac the line break character is \r).

if you type :

abc
Ctrl+D

you will have 4 characters because of the line break at the end of the abc sequence.


NOTE : as other members noticed you are using the wrong formatting character for long type, it must be %ld but you are using %1d (1 instead of l) i think it is a mistake when you copied the code.


hope that answer you question.

younes zeboudj
  • 856
  • 12
  • 22