[英]Question about while(!EOF)
Im reading in values from stdin
and I want to keep reading the file until I have completed reading it all the way, so I am using我从
stdin
读取值,我想继续读取文件,直到我完全读取它,所以我正在使用
while(!EOF){ scanf(...) }
However, the code fragment doesn't seem to do anything,但是,代码片段似乎没有做任何事情,
while(!EOF){
scanf("%d %d %d %d", &imageWidth, &imageHeight, &safeRegionStart, &safeRegionWidth);
printf("---imageWidth=%d imageHeight=%d safeRegionStart=%d safeRegionWidth=%d---\n", imageWidth, imageHeight, safeRegionStart, safeRegionWidth);
totalP = imageWidth * imageHeight ;
totalSafeP = imageHeight * safeRegionWidth;
printf("---total # of pixels: %d Total # of safe Pixels: %d---\n\n", totalP, totalSafeP);
i=1;
while(i!=totalP)
{
i++;
scanf("%d", &pixel);
printf("\nValue of pixel %d", pixel);
}//End for scanning all pixels*/
}//while loop
EDIT: I fixed it编辑:我修好了
while(scanf("%d %d %d %d", &imageWidth, &imageHeight, &safeRegionStart, &safeRegionWidth)==4&&!feof(stdin)) { }
!feof(stdin)
probably isn't necessary. !feof(stdin)
可能没有必要。
EOF
is only an integer constant. EOF
只是一个 integer 常数。 On most systems it is -1
.在大多数系统上,它是
-1
。 !-1
is false
and while(false)
won't do anything. !-1
是false
的, while(false)
不会做任何事情。
What you want is to check the return values of scanf
.你想要的是检查
scanf
的返回值。 scanf
returns the number of successfully read items and eventually EOF
. scanf
返回成功读取项目的数量,最终返回EOF
。
Well, this is easy to answer:好吧,这很容易回答:
EOF is a constant #define
, eg #define EOF -1
. EOF 是一个常数
#define
,例如#define EOF -1
。
So your while(!EOF)
condition will always be false and the loop won't execute.因此,您的
while(!EOF)
条件将始终为 false,并且循环不会执行。 You need to check the return value of scanf
against EOF.您需要根据 EOF 检查
scanf
的返回值。
You need something like:你需要类似的东西:
while(scanf("%d %d %d %d", &imageWidth, &imageHeight, &safeRegionStart, &safeRegionWidth) != EOF){
You have to use a variable to hold a char value that can be potentially EOF
.您必须使用变量来保存可能是
EOF
的 char 值。 Something like..就像是..
while(4==scanf("%d %d %d %d", &imageWidth, &imageHeight, &safeRegionStart, &safeRegionWidth)) {
//do stuff
}
Otherwise.EOF is always false.否则.EOF 总是假的。
The loop will never be entered.永远不会进入循环。
EOF
is a constant value which is -1
(check stdio.h
for this definition). EOF
是一个常数值,它是-1
(检查stdio.h
的定义)。 So !EOF
is 0
which is false, so it will never be entered.所以
!EOF
是0
是假的,所以它永远不会被输入。
To check that if the file has ended or not you can use: if (feof (file_ptr)) break;
要检查文件是否已结束,您可以使用:
if (feof (file_ptr)) break;
while (1)
{
/* Read file */
if (feof (file_ptr))
break;
/* Do work */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.