与if语句中的字符串比较不起作用

我尝试比较从scanf和fscanf获得的两个字符串。 我已经弄明白每个变量里面的内容是什么。 它都显示相同的字符串,但在if语句中与这两个字符串进行比较后,它不起作用并执行else语句。 我的代码出了什么问题?

int main(void) { ... char input[256]; printf("Enter your name: "); scanf("%s",&input); fp = fopen(_FILE,"r+"); for(i=0;i<textlines(_FILE);i++) { fscanf(fp,"%s %d",stuff[i].name,&stuff[i].salary); if(input == stuff[i].name) { // Update name here } else { printf("Not Found"); } } return 0; } 

==只是检查指针是否相等。 请改用strcmp

使用string.h库中的strcmp函数来比较你的字符串

正如其他人所说,你需要使用strcmp来比较字符串(真正的字符数组)。 此外,您不应将name(即&name)的地址传递给scanf()函数。

你有这个:

 char input[256]; printf("Enter your name: "); scanf("%s",&input); .... if(input == stuff[i].name) ... 

更正确的代码将包括以下更改:

 char input[256]; printf("Enter your name: "); scanf("%s", input); .... if (!strcmp(input, stuff[i].name)) .... 

你应该检查stuff [i] .name的定义和使用。 具有%s格式字符的scanf()需要一个简单的char *参数。 strcmp()的参数是const char *但是使用char *很好并且会自动提升。

C比其他语言更灵活,因为它允许您获取变量的地址。 您可以通过这种方式创建指向变量的指针。 但是,声明为数组的变量(如输入)在某种程度上已经是指针。 只有通过提供索引才能取消引用指针。 特别:

 char input[256]; input is a pointer to the storage of 256 char's input can be thought of as a char* variable input[0] is the first char in the array input[1] is the second char in the array input+1 is a pointer to the second char in the array. input+0 (or simply input) is a pointer to the first char in the array. 

&输入不好的Cforms。 您可以将此视为数组的地址,但实际上,输入已经是数组的地址。 这种类型的双重处理变量有一个用途,但你的情况实际上不是其中之一。 在你对数组和指针(以及它们的关系)进行一些练习之前,下面的例子可能有点令人困惑,但它确实展示了可能使用char **变量的位置。

 int allow_access_to_private_data(char ** data) { static char mystring[] = "This is a private string"; if (!data) return -1; *data = mystring; return 0; } int main(int argc, char* argv[]) { char* string; if (!allow_access_to_private_data(&string)) printf("Private data is: %s\n", string); else printf("Something went wrong!\n"); return 0; }