Search code examples
cgetchar

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);
}

Solution

  • 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.