tselios
tselios

Reputation: 63

read string and compare with certain value

I want to read a string from a console application and compare it:

#include "string.h"
#include "stdio.h"
#include "stdafx.h"

char* answer;

int _tmain(int argc, _TCHAR* argv[])
{
   printf("(yes/no):");
   scanf("%s", &answer);
   if (answer=="yes")
   {
      printf("Yes");
   }
   else
   {
      printf("Exiting...");
   }
   return 0;
}

I always get the message Exiting... when I put yes. How is it possible that I read the correct value of yes but it is not detected by the comparison - answer=="yes" -?

Also tried this:

    #include "string.h"
    #include "stdio.h"
    #include "stdafx.h"

    char answer[100];

    int _tmain(int argc, _TCHAR* argv[])
    {
       printf("(yes/no):");
       scanf("%s", answer);
       if (!strcmp(answer,"yes"))
       {
          printf("Yes");
       }
       else
       {
          printf("Exiting...");
       }
       return 0;
    }

this led me to the 2nd option of "Exiting..." as well. What is the error here?

Upvotes: 0

Views: 68

Answers (2)

Haris
Haris

Reputation: 12270

Many problems in your code

1) You did not allocate memory for answer. Do

answer = malloc(100);

Do not forget to free(answer) it later though.

OR

You can also use arrays directly since you do not need dynamic memory

char answer[100];


2) You need to char * to printf() not char **. Do

scanf("%s", answer);


3) Use strcmp to compare strings, not ==.

if (!strcmp(answer, "yes")
{
    printf("Yes");
}

! is there because, strcmp returns 0 when the strings match.


4) You should also check for return values, like here for scanf().

if (scanf("%s", answer) != 1)
{
    printf("scanf failed");
    exit(0);
}


5) You should also mention the number of chars to be read by scanf() to avoid buffer overflow.

scanf("%99s", answer)

For a char array[100] of size 100, one should give 99 to keep place for the null character \0.

Upvotes: 5

Dilip Kumar
Dilip Kumar

Reputation: 1746

To compare strings, you should use strcmp().

That said, answer is not allocated memory. You need to either use an array or use dynamic memory allocation to get the proper memory allocated to this before you can actually use answer.

Basically, you scan statement should look like

scanf("%s", answer);

with proper memory allocated to answer beforehand.

Upvotes: 0

Related Questions