Comparing two strings not working...

So what I have is a piece of code like this:


int newMessages = 0;
for (unsigned int i = 0; i < listToFill.size(); i++)
{

if (listToFill[i].getUnread() == "N") // checking if the message is new
{
newMessages++; // if it is, this variable gets increased
}
// cout << listToFill[i].getUnread() << " "; // this is a test code to make sure the getUnread status exists
}


listToFill is a vector filled with classes, getUnread is a member function of the class that returns the status of the object, which is either "N" for new or "R" for read. Now for some reason, when I print the newMessages variable after this code, it still says 0 instead of 1, meaning it's not comparing the two "N"s properly for some reason.

If I change the operator to != "N", the newMessages variable will then be 5, meaning nothing in the vector's status matches the N. Also if I uncomment the test part code, it outputs: R R R R N, meaning that the strings SHOULD exist in the variable.

getUnread returns a string that is either N or R, and "N" on the right hand of the operator should be a string, so why isn't this comparing the two properly?

Seems so simple, but I can't figure this out. Thanks to anyone who replies!
Last edited on
Post the code for getUnread().

EDIT: preemptively... if getUnread() returns a char*, then you are comparing pointers, not strings, and the comparison will almost certainly always be false.
Last edited on
IGNORE
Last edited on
I'm sorry for wasting your time, I figured it out. I'm an idiot. The getline made it so it had a space " N" instead of "N"

><

Thanks for your help though!
Use
 
if (!strcmp(listToFill[i].getUnread(), "N"))


Your current comparison is probably comparing the addresses of the first character in each string, instead of the string contents.

Note that strcmp() returns zero if the strings are equal, and note that the comparison is case-sensitive. Use strcmpi() if you want it to be case-insensitive.
Topic archived. No new replies allowed.