0

This is the loop in my a4.c main method that calls the patternsearch function:

while(!feof(stdin)) {
scanf("%s", &word); 
patternSearch(grid, word); 
}

For some reason that I can't figure out, this prints the last call to patternsearch twice:

For example, look at my output for test3:

Found "tip" at 0 2, L
Found "pop" at 0 0, D
Found "pop" at 2 0, U
Found "key" at 0 3, D
Found "key" at 2 1, R
"nope" - Not Found
"nope" - Not Found

As you can see, the test result for 'nope' was printed twice. :(

I think my problem is similar to the one stated here: Last line being printed twice (C++) but I'm not sure.

Community
  • 1
  • 1
RockAndaHardPlace
  • 417
  • 1
  • 7
  • 18

2 Answers2

1

Step 1 with any problem involving input: test the return value from the input function.

  1. feof() checks if a prior read resulted in an end-of-file. It does not report about future reads.

  2. Code is having trouble with unexpected results of scanf("%s", &word);, yet code did not check the return value from scanf(). Weak code does not check the return value. Robust code does. Research the proper use of scanf() and its return values.

  3. Do not use "%s" without a width limit.

  4. The & in scanf("%s", &word); is likely not needed. Would need to see word declaration to be sure.

    char word[100];
    while (scanf("%99s", word) == 1) {
      patternSearch(grid, word); 
    }
    
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

The issue here was that feof() only returned true when I actually hit the EOF character.
That means that I was calling scanf(), and hitting the EOF; that means the loop won't iterate again, but I was already in the middle of it.
But scanf() only actually changes the argument I hand it if it successfully reads what I asked; since it failed (by hitting EOF), it won't change the character array, which will still contain whatever it did before (i.e. the previous word).

I checked the return value of scanf(); the number it returns, which is the number of arguments it put a new value into; if that's less than 1, then I didn't actually get a new string (I think it also explicitly returns EOF if it hits the end-of-file; EOF is a #defined constant that's equal to -1 on most platforms, so the <1 check will work anyway).

This is the code that finally worked:

while(!feof(stdin)) {
    if (scanf("%s", &word) < 1)
      break;
    patternSearch(grid, word);
  }
RockAndaHardPlace
  • 417
  • 1
  • 7
  • 18