Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

scanf check for EOF

Status
Not open for further replies.

mcauliff

Programmer
Feb 26, 2007
71
US
How is end of file or no input check done for scanf?

example;

for (n = 0; n < 10; ++n) {
printf("enter a number\n");
scanf ("%d", %int);
if (int == "")
break;
}

 
By including stdio.h and doing the intuitive thing. ;)
Code:
int p = 0;
for (i=0; i < 10 ; i++) {
    printf("\nEnter integer value:");
    scanf(" %d",&p);
    if (p == EOF) {printf("Eof encountered\n");
}
 
What is wrong with this code?

/* scanf check for EOF */

#include <stdio.h>

int main() {
int n, i;
for (i = 0; i < 5; ++i) {
printf ("enter a single digit or hit enter \n");
scanf(" %d", &n);
if (n == EOF)
break;
printf("%d\n", n);
}
return 0;
}
 
scanf returns EOF, it doesn't store it in the result.

As in
Code:
int result = scanf( "%d", &value );
if ( result == EOF ) {
  // yes, th th th th that's all folks
}

--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
On success scanf returns the number of fields successfully converted and assigned (1 in your case).
So any unusual condition (i/o error, EOF etc) test is:
Code:
if (scanf("%d",&n) != 1)
... break ...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top