如何正确使用C比较字符串? [英] How do I properly compare strings in C?

查看:108
本文介绍了如何正确使用C比较字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get a program to let a user enter a word or character, store it, and then print it until the user types it again, exiting the program. My code looks like this:

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

问题是,我不断收到输入字符串的打印,即使用户(检查)输入原始(输入)相匹配。我在比较这两个错误?

The problem is that I keep getting the printing of the input string, even when the input by the user (check) matches the original (input). Am I comparing the two incorrectly?

推荐答案

您不能(有效)比较使用字符串!= = = ,你需要使用 STRCMP

You can't (usefully) compare strings using != or ==, you need to use strcmp:

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

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

The reason for this is because != and == will only compare the base addresses of those strings. Not the contents of the strings themselves.

这篇关于如何正确使用C比较字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆