So, I’ve got the following code (C):
char c = getc(in);
if (c == '(')
...
if (c == '%')
...
if (isdigit(c))
{
int n;
ungetc(c, in);
scanf("%i", &n);
...
}
Everything is all fine and dandy when I’m reading in input from stdin but, when reading in input from from a file, the call to scanf does not terminate.
I added some code around the call to see what’s going on before the call to scanf. One such instance is
c = '0'- the character right after
cis)
Is the buffer not flushing after ungetc or something? What might be happening, that it works fine when the input is stdin but not when its a file? (I’m not that familiar with IO in C).
edit: Should have used fscanf… boy is my face red.
getc()will return EOF when youreach the end or an error occurs so
make sure you check for that. Your
chave to be an int, not a char to be able to distinguish EOF.The same goes for scanf check its
return value for EOF. For scanf the
conversion might also fail,
scanf("%i", &n)should return 1 ifit successfully parsed something
into
nso make sure you check forthat too.1.
You are also operating on
in, asin
getc(in), suggesting you’rereading from a particular FILE* ,
however your scanf call still reads
from stdin.
Use fscanf instead of
scanfthere.