Can someone explain to me why txt3, txt4 and txt4, txt5 are not equal?
Why does (txt3 == txt4) and (txt5 == txt6) give false?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string txt1("EL020GM");
string txt2("EL020GM");
char txt3[] = "EL020GM";
char txt4[] = "EL020GM";
char * txt5 = &txt3[0];
char * txt6 = &txt4[0];
const char * txt7 = "EL020GM";
const char * txt8 = "EL020GM";
if(txt1 == txt2) { std::cout << "yes\n"; } else{ std::cout << "no\n"; }
if(txt3 == txt4) { std::cout << "yes\n"; } else{ std::cout << "no\n"; }
if(txt5 == txt6) { std::cout << "yes\n"; } else{ std::cout << "no\n"; }
if(txt7 == txt8) { std::cout << "yes\n"; } else{ std::cout << "no\n"; }
return 0;
}
Because you can't use == to compare C-style strings. You have to use strcmp():
if (strcmp(txt1, txt2) == 0) ...
That's how you do a string comparison of C-style strings.
Or better yet, use C++ strings.
What your code is doing is asking if the POINTERS are pointing to the same place. They don't. You are not comparing the data being pointed at.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With