没有编译器错误,但某处存在错误

时间:2014-07-03 04:54:16

标签: c loops

我用“gcc -ansi -pedantic -W -Wall -o”编译。编译时我只收到2个错误,这里是:

easter_eggs.c: In function ‘main’:
easter_eggs.c:23:18: warning: multi-character character constant [-Wmultichar]
    if (prompt == 'egg1')
                  ^
easter_eggs.c:23:4: warning: comparison is always false due to limited range of data type [-Wtype-limits]
    if (prompt == 'egg1')

当我运行程序并点击S时,它会显示前2个printf语句,每个语句2次。如果我键入任何内容并按Enter键没有任何反应它只是返回到提示符。即使我输入egg1,它仍然会回复提示。这是来源:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char first_option;
    char prompt[16];

    system("clear");
    system("toilet -f future -F gay Easter Eggs");
    printf("\nFind all the easter eggs and you win. Simple enough.\n");
    printf("Hit S to start and Q to quit\n");
    scanf("%c", &first_option);

    if (first_option == 's')
    {
        while (1)
        {
            printf("To exit hit Ctrl + C\n");
            printf("You must find all easter eggs simply by typing stuff in the prompt below: \n");
            memset(prompt, 0, sizeof(prompt));
            scanf("%16s", prompt);
            getchar();
            if (!strcmp(prompt, "egg1"))
            {
                printf("Found 1\n");
            }
        }
    }

    if (first_option == "q")
    {
        exit(0);
    }

    else
    {
        printf("Invalid input. Press Enter to continue\n");
        getchar();
        main();
    }

    return 0;
}

编辑1:我编辑了源

编辑2:再次更改源。这次我使用strcmp()来比较字符串,而不是==

最后编辑:我设法让它发挥作用。还更新了源以使其工作。感谢所有人对我的耐心。多少天都没有睡觉。 :/

3 个答案:

答案 0 :(得分:2)

阅读有关C编程的更多信息。你对char和字符串感到困惑。

如果要将一个单词作为最多16个字节的字符串读取并使用终止空字节,请使用例如。

  char prompt[16];
  memset (prompt, 0, sizeof(prompt));
  if (scanf("%15s", prompt)<1) return;
  if (!strcmp(prompt, "egg1")) {
     /// found

此外,您使用-Wall进行编译是正确的。但是也要编译调试信息和额外的警告:

  gcc -Wall -Wextra -g easter_eggs.c -o easter_eggs

learn如何使用gdb调试器

另请阅读scanf(3)&amp;的手册页(在Linux终端中输入man man)。 strcmp(3)

答案 1 :(得分:1)

比较char变量时,必须将其与char进行比较。

正如编译器告诉你的那样,你在这里有一个多角色。

strcmp()会帮助你。

答案 2 :(得分:1)

正如其他评论中所述,阅读C.以下是一些建议

  1. 要在C中存储字符串,您必须在分配内存后使用char[]char *
  2. 您无法使用==运算符来比较字符串。请改用strcmp()