tags:

views:

150

answers:

4

I'm having trouble finding the error in the following code:

#include <stdio.h>
#define LOOP    0
#define ENDLOOP 1
main()
{
  int c, loop;
  loop = LOOP;
    while ((c = getchar()) loop != ENDLOOP) {
      if (c == 'e'|| c == 'E') {
        printf ("END LOOP\n");
        loop = ENDLOOP;
      }
      else if (c == 'c' || c == 'C')
        printf ("Cheese\n");
      else 
        printf ("Not Cheese\n");
    }
}

The terminal is giving me this error:

1-1.c: In function ‘main’:
1-1.c:8: error: syntax error before ‘loop’
1-1.c: At top level:
1-1.c:13: error: syntax error before ‘else’
+4  A: 

Are you perhaps missing an operator?

while ((c = getchar()) && loop != ENDLOOP) {
Ignacio Vazquez-Abrams
Jonathan Leffler
+6  A: 

You have a problem here:

((c = getchar()) loop != ENDLOOP)

Should be:

((c = getchar()) && loop != ENDLOOP)

I'd recommend writing it in a totally different way:

#include <stdio.h>
int main()
{
    int c;
    while (c = getchar()) {
        if (c == 'e' || c == 'E') {
            printf ("END LOOP\n");
            break;
        }
        if (c == 'c' || c == 'C') {
            printf ("Cheese\n");
        } else {
            printf ("Not Cheese\n");
        }
    }
    return 0;
}

I think this way has fewer chances to make errors. You might also want to consider using tolower.

Mark Byers
No, those aren't *unbalanced*, though they could be simplified.
Wallacoloo
Was unbalanced: fixed now. And simplified verision provided. I found it too confusing (hence my error initially).
Mark Byers
Your clarification from your update is scarily similar to my own example. :)
mctylr
@mctylr: Yep, when I first saw your comment I thought you were just making a small improvement to my code. But there are subtle differences in whitespace that show it's not a copy.
Mark Byers
Jonathan Leffler
+3  A: 

At least one error is that you're missing an operator here:

 while ((c = getchar()) loop != ENDLOOP)

I assume you mean "AND" and thus it should be:

 while ((c = getchar()) && loop != ENDLOOP)
Mark E
+2  A: 

You can get rid of the ugly loop != ENDLOOP conditional and simplify your program in the process.

#include <stdio.h>

int main()
{
   int c;
   while (EOF != (c = getchar())) {
      if (c == 'e'|| c == 'E') {
         printf ("END LOOP\n");
         break;
      } else if (c == 'c' || c == 'C')
         printf ("Cheese\n");
      else 
         printf ("Not Cheese\n");
   }
   return 0;
}

The EOF not equal comparison makes explicit how getchar() can terminate the while loop. Otherwise the break does if 'e' or 'E' are taken from stdin.

The int in front of main, and the return 0 are to make it clean ANSI C, so basically stylistic, but good style.

mctylr
I find the reversed condition in the while loop perverse (for all some books recommend it - I disagree with those books) - but you _are_ testing for EOF which none of the other solutions does, so +1.
Jonathan Leffler