我试图得到一个程序,让用户输入一个单词或字符,存储它,然后打印它,直到用户再次键入它,退出程序。我的代码是这样的:

#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);   /* obsolete function: do not use!! */
    printf("I will now repeat this until you type it back to me.\n");

    while (check != input)
    {
        printf("%s\n", input);
        gets(check);   /* obsolete function: do not use!! */
    }

    printf("Good bye!");
    

    return 0;
}

问题是,我一直得到输入字符串的打印,即使当用户的输入(检查)匹配原始(输入)。我把两者比较错了吗?


当前回答

    #include<stdio.h>
    #include<string.h>
    int main()
    {
        char s1[50],s2[50];
        printf("Enter the character of strings: ");
        gets(s1);
        printf("\nEnter different character of string to repeat: \n");
        while(strcmp(s1,s2))
        {
            printf("%s\n",s1);
            gets(s2);
        }
        return 0;
    }

这是一个非常简单的解决方案,你可以得到你想要的输出。

其他回答

你不能使用!=或==比较字符串(有用),你需要使用strcmp:

while (strcmp(check,input) != 0)

这样做的原因是!= and ==将只比较这些字符串的基址。而不是字符串本身的内容。

    #include<stdio.h>
    #include<string.h>
    int main()
    {
        char s1[50],s2[50];
        printf("Enter the character of strings: ");
        gets(s1);
        printf("\nEnter different character of string to repeat: \n");
        while(strcmp(s1,s2))
        {
            printf("%s\n",s1);
            gets(s2);
        }
        return 0;
    }

这是一个非常简单的解决方案,你可以得到你想要的输出。

你需要使用strcmp(),你需要#include <string.h>

!=和==操作符只比较这些字符串的基址。不是字符串的内容

while (strcmp(check, input))

示例代码:

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

int main()
{
    char input[40];
    char check[40] = "end\n"; //dont forget to check for \n

    while ( strcmp(check, input) ) //strcmp returns 0 if equal
    {
        printf("Please enter a name: \n");
        fgets(input, sizeof(input), stdin);
        printf("My name is: %s\n", input);
    }

    printf("Good bye!");
    return 0;
}

注1:gets()是不安全的。请改用fgets()

注意:当使用fgets()时,你也需要检查'\n'新行字符

使用比较字符串。

它在string.h库中,非常流行。如果字符串相等,STRCMP返回0。下面是strcmp返回内容的更好解释。

基本上,你需要做的是:

while (strcmp(check,input) != 0)

or

while (!strcmp(check,input))

or

while (strcmp(check,input))

您可以查看这个关于strcmp的教程。

您可以:

使用string.h中的strcmp(),这是更简单的版本

或者如果你想自己卷,你可以用这样的东西:

int strcmp(char *s1, char *s2)
{
    int i;
    while(s1[i] != '\0' && s2[i] != '\0')
    {
        if(s1[i] != s2[i])
        {
            return 1;
        }
        i++;
    }
    return 0;
}

我将像这样使用strcmp():

while(strcmp(check, input))
{
    // code here
}