tags:

views:

32

answers:

2

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

  1. c = '0'
  2. the character right after c is )

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.

+1  A: 
  1. getc() will return EOF when you reach the end or an error occurs so make sure you check for that. Your c have to be an int, not a char to be able to distinguish EOF.

  2. The same goes for scanf check its return value for EOF. For scanf the conversion might also fail, scanf("%i", &n) should return 1 if it successfully parsed something into n so make sure you check for that too.1.

  3. You are also operating on in, as in getc(in), suggesting you're reading from a particular FILE* , however your scanf call still reads from stdin.

    Use fscanf instead of scanf there.

nos
I've confirmed that `getc` and `ungetc` are both successful, and that `c` is definitely a digit which could be scanned back in as a number. I can't check the return value of `scanf` because it doesn't terminate. (When I interrupt the program in the debugger, it is killed in `__kernel_vsyscall__`.)
Pete
You can still write the code tho check the return value of scaf though. See the edit, you're using scanf to read from stdin when you possibly want to read from a file.
nos
Ah! Obviously... Thank you.
Pete
A: 

scanf() will take input from the stdin file descriptor. If redirected, then will take from the appropriate source. getc() will read from any file descriptor. You're mixing inputs from a file and stdin.

You might be more interested in fscanf() to read from your file.

char c = getc(in);
if (c == '(')
   ...
if (c == '%')
   ...
if (isdigit(c))
{
   int n;
   ungetc(c, in);
   fscanf(in, "%i", &n);
   ...
}
Jeff M