Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 618
Dmitriy Potemkin Avatar asked Apr 04 '13 03:04

Dmitriy Potemkin


2 Answers

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])
{
    ...
}
like image 165
Sergey Kalinichenko Avatar answered Sep 27 '22 21:09

Sergey Kalinichenko


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.

like image 22
Rijesh4 Avatar answered Sep 27 '22 23:09

Rijesh4