从 fgetc() 读取输入并使用 printf() 打印
好吧,我确信我在这里遗漏了一些东西,但我不知道它是什么,我希望有人能帮我弄清楚。
我正在从命令行读取输入,并正在编写一个使用 fgetc() 来执行此操作的函数。然而,函数中看似表面的变化会导致其行为完全不同。
这是 main() 函数:
while(1)
{
char* cmd = malloc(sizeof(char) * 80);
printf("Enter command: ");
read_flush(cmd, 80);
printf("%s\n", cmd);
free(cmd);
}
这是 read_flush() 的版本之一:
int read_flush(char* buffer, int count)
{
int i, c;
for(i = 0; i < count; i++)
{
c = fgetc(stdin);
if(c == '\n' || c == EOF)
return i;
buffer[i] = (char)c;
}
return i;
}
这个运行良好。你输入输入,它会把它吐出来。 然而,下一个版本会导致 main 一遍又一遍地打印“Enter command:”,而不给用户输入的机会。
int read_flush(char* buffer, int count)
{
int i, c;
while(i < count)
{
c = fgetc(stdin);
if(c == '\n' || c == EOF)
return i;
buffer[i] = (char)c;
i++;
}
return i;
}
我在这里错过了 fgetc() 的哪些微妙之处?
Okay, I'm sure there's something I'm missing here, but I have no idea what it is and I'm hoping someone could help me figure it out.
I'm reading in input from the command line and was writing a function that uses fgetc() to do so. However, a seemingly superficial change in the function causes it to behave completely differently.
This is the main() function:
while(1)
{
char* cmd = malloc(sizeof(char) * 80);
printf("Enter command: ");
read_flush(cmd, 80);
printf("%s\n", cmd);
free(cmd);
}
And this is one of the versions of read_flush():
int read_flush(char* buffer, int count)
{
int i, c;
for(i = 0; i < count; i++)
{
c = fgetc(stdin);
if(c == '\n' || c == EOF)
return i;
buffer[i] = (char)c;
}
return i;
}
This one works fine. You type in input and it will spit it back out.
However, this next version causes main to just print "Enter command:" over and over without giving the user a chance to enter input.
int read_flush(char* buffer, int count)
{
int i, c;
while(i < count)
{
c = fgetc(stdin);
if(c == '\n' || c == EOF)
return i;
buffer[i] = (char)c;
i++;
}
return i;
}
What subtlety with fgetc() am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试在第二个
read_flush
实现中初始化i
。Try initializing
i
in your secondread_flush
implementation.在第二个版本中,您似乎没有像第一个版本中那样将 i 初始化为零。因此它可能以大于 count 的垃圾值开始,因此循环永远不会执行。
In the second version it looks like you are not initializing i to zero like you do in the first version. So it could be starting with a garbage value larger than count, and thus the loop never executes.
两个版本都有相同的错误。不要在字符串末尾添加 NUL。
malloc 不会初始化它返回的内存。
Both versions have the same error. You don't add a NUL on the end of the string.
malloc does not initialize the memory that it returns.