测试getchar()== EOF不能按预期工作 [英] Testing getchar() == EOF doesn't work as expected
问题描述
我有一个任务写一个C程序,该程序允许用户输入最多20个整数(它将停止接受基于前哨值或达到20个整数的数字)。然后,该程序应按相反的顺序显示数字。
I have an assignment to "Write a C program that allows a user to enter up to 20 integers (it will stop accepting numbers based on a sentinel value or based on the 20-integer limit being reached). The program should then display the numbers in the reverse order of entry."
我决定将前哨值设为 EOF(或CTRL + D / CRTL + Z)。我的代码有一些非常不稳定的行为:
I decided to make my sentinel value "EOF" (or CTRL+D / CRTL+Z). My code has some really erratic behavior:
- 您必须按两次EOF键(这还会创建一个空白条目,该条目被计入
- 第一个条目的第一位被截断。
其他所有内容似乎都没有可以,但是显然这不是理想的结果。下面是我的代码。您能解释出什么问题吗?
Everything else seems to work OK but, this is clearly not the desired results. Below is my code. Can you explain what's wrong?
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;
}
已编辑:
这是我的最终代码,谢谢大家的帮助。
EDITED: Here is my final code, Thank you all for your help:
#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。
The getchar()
call reads (and effectively discards) the first digit because it is not EOF.
您无需测试 scanf()
有效;
for (i = 0; i < MAX; i++)
{
if (scanf("%d", &x[i]) != 1)
break;
}
这时,有 i
数组中的整数;您实际上并不需要在循环中设置 iMax
。您只需在循环退出时进行设置即可。
At this point, there are i
integers in the array; you don't really need to set iMax
in the loop. You could simply set it when the loop exits.
这篇关于测试getchar()== EOF不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!