0

Ive been working on a project all day and I have come to a hault because fscanf isn't working the way I thought it was suppose to.

I am reading a file that contains something like this:

AND 0 3 2

Here is a peice of my code that is giving me problems:

while(fscanf(circuit, "s",cur_gate)!=EOF){
    if(cur_gate[0]=='A'){
            fscanf(circuit,"%d %d %d",&cur_output,&cur_input1,&cur_input2);
            printf("current output: %d\n",cur_output);
            printf("current input: %d current input2: %d\n",cur_input1,cur_input2);

So what I am doing is reading the file and checking if the string = AND (cur_gate). Then if it = 'A', i am reading 3 integers. I want to assign the first integer to cur_output and the second and third to cur_input1 and cur_input2, respectively.

The problem is that its output is:

current output: 0

current input: 0 current input2: 0

While the output should actually be:

current output: 0

current input: 3 current input2: 2

I honestly don't know what's wrong because I did almost the same thing earlier and it worked. Thanks for any help!

DarkLink
  • 355
  • 4
  • 16

2 Answers2

1

fscanf(circuit, "s",cur_gate) will try to scan a literal s character. If you want to scan a string, you'll need something like %s.

This would have been more obvious if you had followed the "check for what you want rather than don't want" rule of scanf:

while (fscanf (circuit, "s",cur_gate) == 1) {

What's happening in your case is that the scan for the literal s is failing but not in such a way that it returns EOF. So, when you come to scanning in the integers (the buffer must have an A as the first character to get inside the if loop), they fail as well because the input stream pointer is still on the A at the start of AND.

As an aside, unless you control the input, using fscanf here can lead to buffer overflow problems. There are probably better ways to do it.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Thank you! I can't believe I didn't catch that. I was so focused on the inside of the while loop that I overlooked that. If you can't tell I am very much a rookie. Thanks – DarkLink Nov 04 '15 at 04:39
  • @Ryan, we *all* were once though, for us old farts, it's sometimes hard to recall :-) – paxdiablo Nov 04 '15 at 04:40
0

Try this :

while(fscanf(circuit, "%s",cur_gate)!=EOF){
    if(cur_gate[0]=='A'){
            fscanf(circuit,"%d %d %d",&cur_output,&cur_input1,&cur_input2);
            printf("current output: %d\n",cur_output);
            printf("current input: %d current input2: %d\n",cur_input1,cur_input2);

Changes :

"s" -> "%s"
Akhil Thayyil
  • 9,263
  • 6
  • 34
  • 48