+ 1

Why inputing 'a' wouldn't make the output 1?

In the following code inputing 'a' wouldn't make name[count] == a as true. Does anyone know why it wouldn't be true? #include <stdio.h> int main(void) { char name[1000][14]; int count = 0; scanf("%s", &name[count]); printf("%s\n", name[count]); printf("%s\n", "a"); printf("%d", name[count] == "a"); return 0; } If I input a this is what I get. a a a 0

30th Apr 2021, 3:27 PM
0900 lop
0900 lop - avatar
7 Réponses
+ 2
First, remove & before name[count] in scanf(). name[count] is already an address. Second, in order to compare 2 strings, you should use strcmp(). == will compare 2 addresses rather than the content. In order to use strcmp(), you need to #include <string.h>. strcmp() returns 0 if 2 strings are equal. So you can do: printf("%d", strcmp(name[count], "a") == 0);
30th Apr 2021, 3:39 PM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 2
You should compare to the character literal 'a' instead of comparing to the string literal "a"
30th Apr 2021, 3:34 PM
Hape
Hape - avatar
+ 2
Then you should use the function strcmp() from <string.h> which compares two strings and returns 0 if they are equal
30th Apr 2021, 3:39 PM
Hape
Hape - avatar
+ 1
Then how about if I want to compare name[count] and "aa"?
30th Apr 2021, 3:36 PM
0900 lop
0900 lop - avatar
+ 1
CarrieForle strlen returns the length and does not compare
30th Apr 2021, 3:42 PM
Hape
Hape - avatar
0
Hape oops, that was a typo. Corrected.
30th Apr 2021, 4:00 PM
你知道規則,我也是
你知道規則,我也是 - avatar
0
Thank you so much!
1st May 2021, 1:16 AM
0900 lop
0900 lop - avatar