Search code examples
cstdineof

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

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.


Solution

  • 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.