Program code =》
Code:char c[20] ; gets(c); char match[20] = "Cat"; if ( c == match) { puts("You entered Cat"); } else { puts("Something else entered."); }
Input: Cat
Output: Something else entered.
Program code =》
Code:char c[20] ; gets(c); char match[20] = "Cat"; if ( c == match) { puts("You entered Cat"); } else { puts("Something else entered."); }
Input: Cat
Output: Something else entered.
== doesn't work for char arrays, use strcmp instead.
Yeah sure i did that but when i do
Inside if test expression i get an compilation error saying the function strcmp should have a prototype.Code:strcmp(c, match)
Add #include <string.h> to the top and then try again. Also, don't use gets() for the same reasons you learned in the other thread.
It's still not working showing only the else part irregardless whatever the input is:
Here is my code
Please take a look, and give me the solution. It would really be appreciated.
Yeah. fgets() will leave the '\n' in the string where enter was pressed. You can remove it with additional code.
See for example this page.
You can't just throw in a library function call and expect it to work. You need to actually read about how the function works and use it correctly. For instance, if you read about strcmp you would learn that you need to include string.h to use it. Also, you would learn that it returns 0 if the strings are equal, so it's usually used like this:
And you need to use fgets instead of the (no longer in the modern language) gets. But fgets leaves the newline in the string, so you'll either have to remove it or add a newline to your test string. A good way to remove it:Code:if (strcmp(a, b) == 0) ; // strings are equal else ; // strings are not equal
BTW, your editor looks like it's from 30+ years ago. Are you a time traveller?Code:int len = strlen(s); // strlen requires string.h if (s[len - 1] == '\n') s[--len] = '\0';
Explode the sunlight here, gentlemen, and you explode the entire universe. - Plan 9 from Outer Space
For windows - download free version of VS2017
Downloads | IDE, Code, & Team Foundation Server | Visual Studio
And choose Community Edition
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler