C: How to compare two strings? [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-02 04:13:37

问题


Edit: This is a duplicate and I've flagged it as such. See [question] Why is "a" != "a" in C?

So I'm trying to print out a specific message depending on a field within a struct. The field contains the string "1".

Whenever I run printf("%s", record.fields[2]); the output is 1; I've no format warnings.

However, when I check the field against the corresponding string (in this case, "1"), it fails the check:

if (record.fields[2] == "1") {
    printf("The field is 1!");
}

回答1:


You need to use strncmp to compare strings:

if (strncmp(record.fields[2], "1", 1) == 0) ...

You need to compare to zero, because strcmp returns zero when two strings are identical.

However, it looks like you are not comparing strings: rather, you are looking for a specific character inside the string. In this case, you need to use a character constant instead of a string literal (with single quotes):

if (record.fields[2] == '1') ...


来源:https://stackoverflow.com/questions/16116012/c-how-to-compare-two-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!