gpt4 book ai didi

c - 测试 getchar() == EOF 没有按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:57 24 4
gpt4 key购买 nike

我有一个任务是“编写一个允许用户输入最多 20 个整数的 C 程序(它将停止接受基于标记值或达到 20 个整数限制的数字)。然后程序应该以输入的相反顺序显示数字。”

我决定将标记值设置为“EOF”(或 CTRL+D/CRTL+Z)。我的代码有一些非常不稳定的行为:

  1. 您必须按 EOF 键两次(这也会创建一个计入数组的空白条目。
  2. 第一个条目的第一个数字被截断。

其他一切似乎都正常,但这显然不是预期的结果。下面是我的代码。你能解释一下哪里出了问题吗?

main() {
int i,iMax;
double dblMean;
int x[MAX];

printf("Please Enter Up to 20 Integers\n");

for (i=0; i<MAX; i++)
{
printf("%d.> ",i+1);
if (getchar() == EOF) /* Check for CTRL+D OR CTRL+Z */
break; /* Exit loop if EOF entered :: Must be pressed twice and eats first character of first entry */
scanf("%d",&x[i]);
iMax=i;
}

printf("\nYou entered %d numbers\n",iMax+1); /* Should be i+1 but EOF had to be entered twice */
printf("\nIndex Item Reverse Item\n");
for (i=0; i<=iMax; i++)
printf("%3d%4c%8d%9c%11d\n",i,' ',x[i],' ',x[iMax-i]);
return 0;

编辑:这是我的最终代码,谢谢大家的帮助:

#include <stdio.h>
#include <stdlib.h>
#define MAX 20
int main()
{
int i,iMax;
int x[MAX];

printf("Please Enter Up to 20 Integers\n");

for (i=0; i<MAX; i++)
{
printf("%d.> ",i+1);
if (scanf("%d",&x[i]) != 1) /* Checks for CTRL+D OR CTRL+Z */
break; /* EOF returns -1 and loop will be exited */
iMax=i; /* iMax must be set for second loop to exit properly */
/* Can sizeof x be used instead for second loop? */
}

printf("\nYou entered %d numbers\n",iMax+1); /* Displays number of items entered... Will be <= MAX*/
printf("\nIndex Item Reverse Item\n");
for (i=0; i<=iMax; i++) /* Why wont 'for (i=0; i<=sizeof x; i++)' work? */
printf("%3d%4c%8d%9c%11d\n",i,' ',x[i],' ',x[iMax-i]);
return 0;
}

最佳答案

getchar() 调用读取(并有效丢弃)第一个数字,因为它不是 EOF。

您没有测试 scanf() 是否有效;你应该。

for (i = 0; i < MAX; i++)
{
if (scanf("%d", &x[i]) != 1)
break;
}

此时,数组中有i个整数;你真的不需要在循环中设置 iMax 。您可以在循环退出时简单地设置它。

关于c - 测试 getchar() == EOF 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13005207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com