Question about while(!EOF)

三世轮回 提交于 2019-12-13 01:14:36

问题


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.


回答1:


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.




回答2:


Well, this is easy to answer:

EOF is a constant #define, e.g. #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){



回答3:


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.




回答4:


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 */
}


来源:https://stackoverflow.com/questions/6275558/question-about-whileeof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!