所以我试图制作一个类似选择的代码,您可以在其中键入一些内容来运行命令,然后键入其他内容来运行其他命令,并且我尝试使用 void 命令来使用函数来执行此操作,因为我试图学习并弄清楚如何使用它,但由于某种原因,我不断收到此错误消息,我并不真正理解它的含义或如何解决它(这可能是显而易见的事情,但我仍在学习)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char commandA[20];
char commandB[20];
char click [20];
scanf("%s",click);
if (click=commandA){
command1();
} else if (click=commandB){
command2();
}
}
void command1(){
printf("i don't know what to type here ");
}
void command2(){
printf("i don't know what to type here x2");
}
}
我希望能够键入 commandA 并获取第一条 printf 消息,我期望能够键入 commandB 来获取第二条 printf 消息,以下是我收到的其他警告和错误:
|11|error: assignment to expression with array type|
|12|error: assignment to expression with array type|
|11|warning: implicit declaration of function 'command1' [-Wimplicit-function-declaration]|
|12|warning: implicit declaration of function 'command2' [-Wimplicit-function-declaration]|
|14|warning: conflicting types for 'command1'|
|16|warning: conflicting types for 'command2'|
最佳答案
第一个错误是因为您在 if
语句中使用了 =
而不是 ==
。 =
用于赋值,==
用于比较是否相等。但为了比较字符串,您必须使用 strcmp()
函数;如果您使用==
,它只是比较数组的地址,而不是内容。
关于隐式声明的错误是因为您将command1
和command2
的定义放在了main()
之后。 C 要求在使用函数之前定义或声明函数,因此您要么必须将 main()
向下移动,要么将函数原型(prototype)放在它之前。
您还需要初始化commandA
和commandB
。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void command1(){
printf("i don't know what to type here ");
}
void command2(){
printf("i don't know what to type here x2");
}
int main()
{
char commandA[20] = "cmdA";
char commandB[20] = "cmdB";
char click [20];
scanf("%s",click);
if (strcmp(click, commandA) == 0){
command1();
} else if (strcmp(click, commandB) == 0){
command2();
}
}
关于c - if 语句中使用的 C 函数中对数组类型表达式进行赋值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300103/