Is it possible to use the string as a condition to function if in c++?

+2 votes
asked May 29 by Randy Gunawan (180 points)

Like this:

#include <iostream>

using namespace std;

int main()
    char a[20];
    cin.getline (a, sizeof(a));
    if (a=="EVEN")
        cout << "Even number";
        cout << "Odd number";

    return 0;

Is the code above correct?

If that's true, why every time I try the results are always false.

Please help me.smiley Thank youangel

2 Answers

0 votes
answered May 31 by shyam (570 points)
selected May 31 by Randy Gunawan
Best answer
Yes, You can use string inside 'if condition'.

Change you're if condition with,

if (a==string("EVEN"))
commented May 31 by Randy Gunawan (180 points)
Thank you very much shyham.
I feel very helped thanks to your answer.
Will you be my tutor? I really appreciate your help if you want.
If you want, let's switch id lines or Instagram.
Thank you
commented May 31 by shyam (570 points)
You are welcome.
How can I contact you?
0 votes
answered Jun 4 by Peter Minarik (7,830 points)

why every time I try the results are always false.

This is, because when you compare a "C string" (not a c++ std::string object!), then what you really do is comparing two char * or const char *.

This means, you do not really check if two c-strings have the same characters in the same order, but rather you compare pointers, whether they point to the same place in memory.

If you want to compare strings in C, you should use strcmp(str1, str2) or strncmp(str1, str2, num_chars_to_compare) or similar methods.

In C++, you can freely compare std::string objects as they are not pointers.

Note: if (a == std::string("EVEN")) works, because what it does is converts the c-string to c++string (via the std::string constructor) and the equality operator will know how to compare a c-string to a c++ string (thanks to the c++ string's specification, how to compare it to a const char *).

For reference:


Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.