How do I simply compare characters in C++?

Dmitriy Potemkin picture Dmitriy Potemkin · Apr 4, 2013 · Viewed 97.4k times · Source

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.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Apr 4, 2013

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])
{
    ...
}