Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

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

+2 votes
asked May 29, 2020 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";
    }
    else
    {
        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, 2020 by shyam (570 points)
selected May 31, 2020 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, 2020 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, 2020 by shyam (570 points)
You are welcome.
How can I contact you?
0 votes
answered Jun 4, 2020 by Peter Minarik (84,720 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:

  1. http://www.cplusplus.com/reference/cstring/strcmp/
  2. http://www.cplusplus.com/reference/cstring/strncmp/
  3. http://www.cplusplus.com/reference/string/string/

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.
...