+ 2

How to put an if condition with string input?

#include <stdio.h> int main() { char s[20]; scanf("%s",s); if(s=="question") { printf("answer"); } return 0; } I don't understand why it doesn't work. Please help. Thanks

28th Feb 2020, 2:19 PM
Cristian Daraban
Cristian Daraban - avatar
3 odpowiedzi
+ 7
First: #include <string.h> You use strcmp from there. if(!strcmp(s, "question")) .... strcmp returns 0 if the strings are equal, that's why 'not' (!).
28th Feb 2020, 2:34 PM
HonFu
HonFu - avatar
+ 6
String comparison in C is done by the use of strcmp function, which means you need to include <string.h> header. Reference: http://www.cplusplus.com/reference/cstring/strcmp/
28th Feb 2020, 2:35 PM
Ipang