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
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.
EOF
is only an integer constant. On most systems it is -1
. !-1
is false
and while(false)
won't do anything.
What you want is to check the return values of scanf
. scanf
returns the number of successfully read items and eventually EOF
.
Well, this is easy to answer:
EOF is a constant #define
, eg #define EOF -1
.
So your while(!EOF)
condition will always be false and the loop won't execute. You need to check the return value of scanf
against EOF.
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
. Something like..
while(4==scanf("%d %d %d %d", &imageWidth, &imageHeight, &safeRegionStart, &safeRegionWidth)) {
//do stuff
}
Otherwise.EOF is always false.
The loop will never be entered. EOF
is a constant value which is -1
(check stdio.h
for this definition). So !EOF
is 0
which is false, so it will never be entered.
To check that if the file has ended or not you can use: if (feof (file_ptr)) break;
while (1)
{
/* Read file */
if (feof (file_ptr))
break;
/* Do work */
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.