if (answer == "word") printf("It's correct");

I have a problem. I need to get from user an answer, for example yes or no, but I can't.
I did this, but it doesen't work.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <conio.h>
using namespace std;
int main()
{
    char answer[4];
    printf("Do you have a car?(yes/no)");
    scanf("%c", answer);
    if(answer == "yes") printf("Cool...");
    if(answer == "no") printf("You should buy one.");
    printf("Press any key to continue...");
    getch();
}

If anyone can help me, please explain how, with the code modified so as to understand. Thanks in advance!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

int main()
{
    std::string answer;
    std::cout << "Do you have a car?(yes/no)";
    std::cin >> answer;
    if(answer == "yes")
        std::cout << "Cool..." << std::endl;
    else if(answer == "no")
        std::cout << "You should buy one." << std::endl;
}
Last edited on
You are entering only a character

scanf("%c", answer);

but trying compare string literals that are converted to pointers to their first elements.

if(answer == "yes") printf("Cool...");

This expression answer == "yes" will be never equal because answer and "yes" have different addresses in memory.

Instead you should use C string function strcmp provided that you entered a string literal.

EDIT: also take into account that function scanf is an unsafe function.
Last edited on
Thank you very much, I figured it now.
If you must use C rather than C++, then use strcmp()
Note: the scanf() statement changed from "%c" to "%3s".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <string.h>
#include <conio.h>

using namespace std;
int main()
{
    char answer[4];
    printf("Do you have a car?(yes/no)");
    scanf("%3s", answer);
    if (!strcmp(answer, "yes"))
        printf("Cool...");
    if (!strcmp(answer, "no"))
        printf("You should buy one.");
    printf("Press any key to continue...");
    getch();
}


http://www.cplusplus.com/reference/cstdio/scanf/
http://www.cplusplus.com/reference/cstring/strcmp/
Chervil, you deserve a big THX!
Topic archived. No new replies allowed.