Vectors in if statements not working

I have a problem. I am trying to search for a letter in an entered variable.
Here I have typed 'ABC' into the console for 'message'.


string message;

vector<char> letters(message.begin(), message.end());

cout << letters[0] << endl;

//All letters as first letter
if (&letters[0] == "A")
{
cout << "A" << endl;
}
etc...
if(&letters[1] == "A")
etc...

When it reaches 'cout << letters[0] << endl;' it shows the first letter of the word, but when it reaches the if statement, it doesn't even fire or print "A". I have tried using arrays, chars, strings and vectors. None work. I also haven't found anything about vectors not firing in if statement on any forums... So I guess this is something new.

Here's something weird:

string newString = "ABC";
cout << newString[0] << endl;

This is basically what I did for the strings. Strangely, newString[0] prints as ABC, not as A. If I use newString[1], it doesn't print anything. I don't understand why this is as it should print "B".

Thank you!
Last edited on
if (&letters[0] == "A")
This says: If the ADDRESS of the first element of the vector is equal to "A"...

I suspect you wanted:
if (letters[0] == "A")
which says: If the first element of the vector is equal to "A"...

Strangely, newString[0] prints as ABC, not as A. If I use newString[1], it doesn't print anything. I don't understand why this is as it should print "B".

That's exactly what does happen - https://ideone.com/1eEkcb
I suspected that that was the problem. I tried removing the ampersand before, but an error would say that '==' was not compatible. As soon as I added the ampersand it went away.
If you're trying to compare to a single char, then use 'A'. 'A' is a char, "A" is a char-pointer (so a memory address), pointing at the start of some memory containing an array of characters.

if (letters[0] == 'A')
Last edited on
Topic archived. No new replies allowed.