EOF Question

J

jobo

Hey,

I'm trying to detect the EOF of the file I pass to my scanf function.
Does anyone know why my if statement isn't triggering? Thanks.

int puzzle[9][9]; // Puzzle data structure
int i, j, count; // Iteration variables
int temparr[81];
char x;
int test;
count = 0;
while (count < 82){

scanf("%c", &x);
if (x == EOF) {
printf("END!");
printf("%d", count);
return 0;
}
test = x;
if (test >= 48 && test <= 57) {
test = test - 48;
temparr[count]= test;
count++;
}
}
 
S

Simon Biber

jobo said:
Hey,

I'm trying to detect the EOF of the file I pass to my scanf function.
Does anyone know why my if statement isn't triggering? Thanks.

int puzzle[9][9]; // Puzzle data structure
int i, j, count; // Iteration variables
int temparr[81];
char x;
int test;
count = 0;
while (count < 82){

scanf("%c", &x);
if (x == EOF) {

If your scanf encounters EOF, it has failed to get a character.
Therefore it does not store anything in x, but rather returns 0 to
indicate that none of the fields were matched. You should be testing the
returned value of scanf, not the value of x after scanf has run.

if(scanf("%c", &x) == 0)
{
printf("END! %d\n", count);
return 0;
}

printf("END!");
printf("%d", count);
return 0;
}
test = x;
if (test >= 48 && test <= 57) {
test = test - 48;

This code assumes an ASCII-based character set. It should be replaced by
portable code (which requires #include <ctype.h>).

if(isdigit((unsigned char)test)) {
test = test - '0';
...
temparr[count]= test;
count++;
}
}
 
S

Simon Biber

Simon said:
If your scanf encounters EOF, it has failed to get a character.
Therefore it does not store anything in x, but rather returns 0 to
indicate that none of the fields were matched. You should be testing the
returned value of scanf, not the value of x after scanf has run.

if(scanf("%c", &x) == 0)
{
printf("END! %d\n", count);
return 0;
}

Replying to myself here: sorry, I misremembered what scanf returns. If
an end-of-file condition or other input failure is encountered before
any conversion occurs, it will actually return EOF. So change that to:

if(scanf("%c", &x) == EOF)

or even:

if(scanf("%c", &x) != 1)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top