我在比较 if
子句中的 char 和“some text”时遇到了问题。
有代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *start[99];
printf("Welcome to MyOS 1");
printf("\n" "#: ");
scanf("%[98]", &start);
if (&start == "help")
{
printf("All commands:" "File" "Calculator");
}
}
最佳答案
start
是一个指向 char 的指针数组,您可能需要一个 char 数组。所以改变
char *start[99];
到
char start[99];
并将 scanf("%[98]", &start);
更改为 scanf("%[98]", start);
要比较 C 字符串,请使用 strcmp()
。所以改变
if (&start == "help")
到
if ( strcmp(start, "help") == 0 )
如果你想阅读行,使用fgets()
而不是 scanf()
。
启用编译器警告也会有所帮助。对于您的代码,GCC 问题:
warning: format ‘%[98’ expects argument of type ‘char *’, but argument 2 has type ‘char * (*)[99]’ [-Wformat=]
warning: comparison of distinct pointer types lacks a cast
warning: comparison with string literal results in unspecified behavior [-Waddress]
关于C 中的 Char 和 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34254587/