Reputation: 63
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
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];
char *
to printf()
not char **
. Do
scanf("%s", answer);
strcmp
to compare strings, not ==
.
if (!strcmp(answer, "yes")
{
printf("Yes");
}
!
is there because, strcmp
returns 0
when the string
s match.
scanf()
.
if (scanf("%s", answer) != 1)
{
printf("scanf failed");
exit(0);
}
char
s 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
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