Whats wrong with my code?

#include <stdio.h>

main()
{
char x[10];
printf("Enter [True/False] : ");
scanf("%s", x);
if(x=="true")
printf("Great..\n");
else
printf("What's wrong?\n");
}

result:

root@invecta:~# gcc -o result if.c
root@invecta:~# ./result
Enter [True/False] : true
What's wrong?
root@invecta:~#

For various reasons, strings don't work like you expect in C. It's really best to simply see strings as arrays with a special value at the end, and treat them accordingly. For comparison, the strcmp function in <string.h> is what you would typically use to compare two strings:

if (strcmp(x, "test") == 0)
  printf("Great...\n");
else
  printf("What's wrong?\n");

Of course, you could also do it yourself with a loop, but that's silly when the standard library does it for you.

also even if you dont use the <string.h> header file, it will still work..
here is a piece of the program,

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
           main()
           {
                     char x[10];
                      clrscr();
                       printf("\n Enter [ True /False ] ");
                        scanf("%s",x); /* but not you can also use the " gets(x) " instead of the "scanf("%s",x);  */
                    
                                  if(strcmp(x,"true")==0)
                                     {
                                         printf("Great .. \n");
                                          getch(); /* this helps to hold the output for the IF statement  */
                                            }
                                          else
                                          {
                                                  printf("Whats wrong.. \n ");
                                                       getch();
                                                       }
                                                    return (0);
                                                        getch(); 
                                               }
This article has been dead for over six months. Start a new discussion instead.