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

Time:09-24

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?

CodePudding user response:

Your code is using arrays and pointer. 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.

CodePudding user response:

Arrays do not have the comparison operator. In fact in this expression

name == "Shah Bhuiyan"

there are compared two pointers (due to the implicit conversion of array designators to pointers to their first elements): the first one is a pointer to the first character of the character array name and the second one is a pointer to the first character of the string literal.

As the array and the string literal occupy different extents of memory the comparison of the addresses will always evaluate to false.

You need to use the standard C string function strcmp to compare two strings.

#include <cstring>

//...

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

If you want to use the equality operator == then instead of the character array use an object of the type std::string.

CodePudding user response:

You could use std::getline to read into std::string instead of C-style char buffer.

  • Related