开发者

Learning C (via K&R) using xcode

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 (?) progr开发者_Go百科am...

#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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜