views:

202

answers:

1

Hi, I'm learning C with The C Programming Language (K&R).

Since I don't particularly want to bob back and forth between a text editor and running gcc, I've decided to use xcode as an IDE. So far, I've been able to follow the book's examples without a problem up until section 1.5.2.

When given the valid (?) program...

#include <stdio.h>

void main()
{
    long nc;

    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%ld\n", nc);
}

...I receive no final output telling me how many characters were in my input. I am entering my input via the xcode console window.

Upon some debugging, it looks like my program gets stuck in the while loop, and never encounters the EOF token. To accommodate for this, I've instead substituted a newline as the new condition, by replacing EOF with "\n", which also does nothing and gives me a int to pointer comparison warning.

What am I doing wrong here?

Will I be able to follow K&R using xcode?

+8  A: 

Type ^D (control-d) to send an EOF.

If you want to break on a newline, you need to compare the return value of getchar to '\n', not "\n". The former is the actual char value of a newline; the latter is a pointer to a char with that value. If that doesn't make sense to you yet, don't worry, it will once you've read more.

Stephen Canon
I tested this and it works perfectly.
Alex Brown
Yes! Thanks a ton!
deeb