“C 编程语言”的非常基本的示例代码没有像预期的那样工作?
我是一名经验丰富的 Java 开发人员,在学习 C 语言以进行计算机科学研究时遇到很多问题。我尝试了很多人推荐的《C 编程语言》一书。
但我在使用最简单的东西(例如 EOF 与 getchar() 结合使用时遇到了问题)。这是代码:
#include<stdio.h>
main()
{
int i = 0;
while (getchar() != EOF)
{
++i;
printf("Count of characters is %d", i);
}
}
我正在使用 Mac OS X Lion,并使用“cc”命令和“./a.out”在终端中运行,就像书中描述的那样运行文件。我得到的是:
- 总是过多地计算一个字符,
- 而 while 循环永远不会结束!它只是在到达输入结束后等待另一个输入......
我真的不知道可能是什么问题。有人可以帮忙吗?
I'm a middle experienced Java developer and have many problems learning the C language for my computer science study. I try it with the book "The C Programming Language" which many people seem to recommend.
But I've got problems with the simplest stuff like the EOF in combination with getchar(). Here's the code:
#include<stdio.h>
main()
{
int i = 0;
while (getchar() != EOF)
{
++i;
printf("Count of characters is %d", i);
}
}
I'm working with Mac OS X Lion and use the "cc" command with "./a.out" for running in terminal, like described in the book to run the file. And what I get is:
- Always counting one character too much
- the while loop never ends! it just waits for another input after reaching end of input ...
I really have no idea what could be the issue. Can someone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能是换行符(输入/返回)。
您可能没有发出输入结束信号。您应该使用
CTRL-D
来执行此操作。That could be the newline (enter / return).
You are likely not signaling end of input. You should be using
CTRL-D
to do so.当你输入一个字符,比如“6”,然后点击回车(等于\n),那么命令“6\n”就会被发送,所以它是2个字符。如果只按 Enter 键,则“i”将增加 1。EOF
表示文件结束,相当于 ctrld+D。如果您读取文本文件,它会很有用。否则就等于说“永远”。
When you type a character, such as "6" and you click enter (which is equal to \n), then the command "6\n" is sent, so it is 2 characters. If you just press enter, then 'i' will be increased by 1.
The EOF means end of file and its equivalent to ctrld+D. It is useful if you read a text file. Else it is the same as saying "Forever".