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

#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(input1,input2);你应该使用名为#include<string.h>的头文件

试试下面的代码:

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

int main() 
{ 
    char s[]="STACKOVERFLOW";
    char s1[200];
    printf("Enter the string to be checked\n");//enter the input string
    scanf("%s",s1);
    if(strcmp(s,s1)==0)//compare both the strings  
    {
        printf("Both the Strings match\n"); 
    } 
    else
    {
        printf("Entered String does not match\n");  
    } 
    system("pause");  
} 

您可以:

使用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
}

你不能使用!=或==比较字符串(有用),你需要使用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'新行字符