This question already has an answer here:
- Why is “a” != “a” in C? 11 answers
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!");
}
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