尝试用 C 编程,在 Y 类型错误之前得到预期的 x

Trying programming with C, Getting Expected x before Y type error

我正在尝试 C(自学和使用 The New Boston 指南),但尝试简单地问这些问题,然后如果答案匹配,则打印 X 或 Y。

关于我正在做的事情,我已经注释掉了你的年龄,我不需要它,如果你删除 if 语句并且只打印 Hi, firstName 就可以工作,我可以看到你是你的年龄等

我得到的错误是:

||=== Build: Debug in TestProject (compiler: GNU GCC Compiler) ===|
C:\Users\admin-jb\Desktop\TestCProject\TestProject\main.c||In function
'main':|
C:\Users\admin-jb\Desktop\TestCProject\TestProject\main.c|21|warning: implicit declaration of function 'If' [-Wimplicit-function-declaration]|
C:\Users\admin-jb\Desktop\TestCProject\TestProject\main.c|22|error: expected ';' before '{' token|
C:\Users\admin-jb\Desktop\TestCProject\TestProject\main.c|33|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build failed: 1 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|

使用 Code::Blocks 13.12

有什么想法吗?

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

int main()
{
    char firstName[20];
//    int  yourAge;
    char excelLike[20];


    printf("Please Enter Your Name?\n");
    scanf("%s", firstName);

//    printf("How old are you?\n");
//    scanf("%d", &yourAge);

    printf("Do you like Excel?\n");
    scanf("%s", excelLike);

    If(strcmp(excelLike, "yes") == 0)
        {
        printf("Hey, %s I love Excel too!!\n", firstName);
        }
    else
        {
        printf("Hey %s, pfft nor do I, its rubbish!\n", firstName);
        }
    return 0;
}

C 关键字 区分大小写 。使用 if 而不是 If.

相关:来自 C11 标准,章节 §6.4.1,关键字

The above tokens (case sensitive) are reserved (in translation phases 7 and 8) for use as keywords, and shall not be used otherwise.....

根据您的用法,编译器无法将关键字 ifIf 相匹配,并且无法将 If 视为函数调用,这在您的案例中未定义。因此您会收到错误消息。

也就是说,

  1. main() 的推荐签名是 int main(void)
  2. 您应该限制 scanf() 的输入字符串长度以避免可能的缓冲区溢出。你应该使用 like

    scanf("%19s", firstName);
    
  3. 始终检查 scanf() 的 return 值是否成功。
C:\Users\admin-jb\Desktop\TestCProject\TestProject\main.c|21|warning: implicit declaration of function 'If' [-Wimplicit-function-declaration]|

您正在使用 If 而不是 if。 C 区分大小写,这意味着您必须小心大小写字母