Jan Krejcar
Jan Krejcar

Reputation: 35

k and r line counting 1.5.3 not working?

I'm having trouble with k&r 1.5.3. Obviously I'm a complete beginner. Below is the code exactly from the book and exactly as I typed it. It compiled fine and runs. It returns characters but just never prints the line count. I'm using ssh into a Ubuntu machine. Can the key on my wife's mac not be interpreted as '\n'?

#include <stdio.h>

/*count lines in input*/

main()
{
     int c, n1;

     n1 = 0;
     while ((c = getchar()) != EOF)
          if (c == '\n')
               ++n1;
     printf("%d\n", n1);
}

Upvotes: 3

Views: 470

Answers (1)

Bart Friederichs
Bart Friederichs

Reputation: 33491

Correct. Mac uses \r as line ending: http://en.wikipedia.org/wiki/Newline

Update your code like this:

#include <stdio.h>

/*count lines in input*/

main()
{
     int c, n1;

     n1 = 0;
     while ((c = getchar()) != EOF)
          if (c == '\r')                      /* use \r for Macs */
               ++n1;
     printf("%d\n", n1);
}

However

When I try to do the same, I have to Ctrl-D to enter an EOF and trigger the program to print the line count.

Upvotes: 5

Related Questions