我试图让一个程序让用户输入一个单词或字符,存储它,然后打印它,直到用户再次键入它,退出程序.我的代码看起来像这样:
#include <stdio.h>
int main()
{
char input[40];
char check[40];
int i=0;
printf("Hello!\nPlease enter a word or character:\n");
gets(input);
printf("I will now repeat this until you type it back to me.\n");
while (check != input)
{
printf("%s\n", input);
gets(check);
}
printf("Good bye!");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题是我不断打印输入字符串,即使用户输入(检查)与原始(输入)匹配.我比较错误吗?
当我调用C字符串比较函数时,如下所示:
strcmp("time","time")
它返回0,这意味着字符串不相等.
任何人都可以告诉我为什么C实现似乎这样做?我认为如果相等,它将返回非零值.我很好奇我看到这种行为的原因.
在下面的代码中,我使用strcmp比较两个字符串,并将此比较作为if语句的条件.使用下面的代码,输出将是hello world,因为字符串"one"等于字符串"two".
#include <stdio.h>
#include <string.h>
char one[4] = "abc";
char two[4] = "abc";
int main() {
if (strcmp(one, two) == 0) {
printf("hello world\n");
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想更改程序,hello world如果两个字符串不同则打印它,所以我改变程序:
#include <stdio.h>
#include <string.h>
char one[4] = "abc";
char two[4] = "xyz";
int main() {
if (strcmp(one, two) == 1) {
printf("hello world\n");
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它不打印任何东西.
这是我的情况的简化:
头文件.h
#DEFINE NUMBER 3
extern char reserved[][];
Run Code Online (Sandbox Code Playgroud)
定义器
char reserved[NUMBER][4] = {"WOW","LOL","K"}
Run Code Online (Sandbox Code Playgroud)
符号.c
#include "header.h"
void theFunctionWithTheError{
if (reserved[1] == "I love stackoverflow"){ /**THE LINE OF THE ERROR*/
return;
}
}
Run Code Online (Sandbox Code Playgroud)
在 sign.c 中,我收到错误Expression must be a pointer to a complete object type
for the wordreserved
你建议我做什么?