Search code examples
c++iostreamc-stringsstring-comparison

Trying to compare a string to a a value with tertiary/conditional operator and it doesn't work


just learning C++ here.

#include <iostream>
#include <string>   

int main()
{
    char name[1000];
    std::cout << "What is your name?\n";
    std::cin.get(name, 50);

    name == "Shah Bhuiyan" ? std::cout << "Okay, it's you\n" : std::cout<< "Who is this?\n";


    
}

So here I wrote a program where I created a variable name[100]. I use the cin iostream object thing to take input for the variable name. If the name is equal to my name (as seen in name == "Shah Bhuiyan" :) then output the first thing or output 'Who are you?'

Instead of outputting 'Oh, it's you' it outputs 'who is this?'

Why doesn't this work?


Solution

  • Your code is using arrays of characters. Any comparisons using == will compare their memory address. Since name and "Shah Bhuiyan" are two distinct arrays of characters, it will always be false.

    The obvious solution is to use c++ strings from the standard library:

    #include <iostream>
    #include <string>   
    
    int main()
    {
        std::string name;
        std::cout << "What is your name?\n";
        std::getline(std::cin, name);
    
        name == "Shah Bhuiyan" ? std::cout << "Okay, it's you\n" : std::cout<< "Who is this?\n";
    }
    

    The std::string type has operators defined that do the right thing here, and will compare the values of each.