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

#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;
}

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


当前回答

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

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

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

其他回答

好的,一些事情,gets是不安全的,应该替换为fgets(input, sizeof(input), stdin)这样你就不会得到缓冲区溢出。

接下来,要比较字符串,必须使用strcmp,其中返回值为0表示两个字符串匹配。使用相等操作符(即。!=)比较两个字符串的地址,而不是它们内部的单个字符。

还要注意,虽然在这个例子中它不会引起问题,但fgets也将换行符'\n'存储在缓冲区中;Gets()不会。如果你比较来自fgets()的用户输入和一个字符串字面值,比如“abc”,它永远不会匹配(除非缓冲区太小,以至于'\n'不能装进去)。

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

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

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

您可以:

使用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
}
    #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");  
}