If you need to validate integer input, then you can't rely on %d alone. It won't catch and reject bad entries like "12w45" - it will successfully convert and assign "12" but will leave "w45" in the input stream to foul up the next read.
There are two ways around this. One is to scan and check the character immediately following the input, like so:
int tmp;
char dummy = 0;
int r;
if ( (r = scanf( "%d%c", &tmp, &dummy )) == 2 )
{
// if following character is whitespace, then this is a valid numeric input
if ( isspace( dummy ) )
temp->data = tmp;
else
{
fprintf( stderr, "non-numeric character '%c' (%d) detected in input\n",
isprint( dummy ) ? dummy : '.', dummy );
fprintf( stderr, "clearing out input stream\n" );
while ( getchar() != '\n' )
; // empty loop
}
}
else if ( r == 1 ) // only thing following numeric input was EOF
{
temp->data = tmp;
}
else if ( r == 0 )
{
fprintf( stderr, "Non-numeric input detected, clearing input stream\n" );
while ( getchar() != '\n' )
; // empty loop
}
else
{
fprintf( stderr, "EOF or error detected on input\n" );
}
A better way to do this in my opinion is to avoid using scanf entirely - read your input as a string using fgets, then use strtol or strtod to perform the conversion:
char buffer[13]; // 11 decimal digits plus sign plus string terminator;
// should be able to store the decimal string representation
// of any 32-bit integer;
if ( fgets( buffer, sizeof buffer, stdin ) )
{
// chk will point to the first character *not* converted by strtol
char *chk;
int tmp = (int) strtol( buffer, &chk, 10 );
if ( !isspace( *chk ) && *chk != 0 )
{
fprintf( stderr, "Detected non-numeric character '%c' (%d) in input\n",
isprint( *chk ) ? *chk : '.', *chk );
}
else
{
temp->data = tmp;
}
}
else
{
fprintf( stderr, "EOF or error on input\n" );
}
When you're doing this kind of validation, use a temporary to store the converted value until you've finished; do not update your actual target until you know the value is good.
fprintfprints to a file, so you need to tell it which file. Did you perhaps meanprintf(no leading f ?datamember oftemp, which isNULL... can you please give a more precise description of what output you actually get (actual behavior) in addition to the desired behavior?