Dmitriy Potemkin
Dmitriy Potemkin

Reputation: 131

How do I simply compare characters in C++?

I have the following code:

#include <iostream>
using namespace std;
int main()
{
    char fg;
    cin>>fg;
    char x[20];
    x[0]='0';
    if(fg=x[0])
    {
        cout<<"It's true!"<<endl;
        return true;

    }
    cout<<"It's false!"<<endl;
    return false;
}

No matter what input I give, true is always returned. Is my syntax off? Any help would be appreciated.

Upvotes: 13

Views: 128574

Answers (2)

Rijesh4
Rijesh4

Reputation: 31

Within if statement use ==. For Eg:

if (fg == x[0]) {
    //...........   
}

== compares, but = makes fg equal to x[0], and that's why you get true every time.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

In C++ you use == for comparison. The = is an assignment. It can be used in the condition of an if statement, but it's going to evaluate to true unless the character is '\0' (not '0', as it is in your case):

if(fg == x[0])
{
    ...
}

Upvotes: 19

Related Questions