开发者

C newbie can't find Syntax Error

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’


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.


Are you perhaps missing an operator?

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


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)


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.


#include<stdio.h>
#include<conio.h>

int x,y,z;
int large();
int main()
{
    printf("Enter the number");
    scanf("%d%d%d",&x,&y,&z);
    large();
    return 1;
}
int large()
{
    printf("large is %d\n",x);
}
{
    else if (y>x;&&y>z)
    {
    printf("%d the larger\n",y);
    }
    else
    {
    printf("%d larger is",x);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜