user14043389
user14043389

Reputation:

How to test if a string character equals a character

I'm allowing the user to insert a string time that contains a time. An example of the format would be 08:10:45AM. I'm testing if the 8th character is either "A" or "P".

Here is my code:

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    string time;
    cin >> time;

    if (time[8] == "A") {
      // do stuff
    }

    return 0;
}

However, I receive this error: "comparison between pointer and integer ('int' and 'const char *"

Does anyone know how to fix this?

Any help would be greatly appreciated :)

Upvotes: 0

Views: 845

Answers (1)

tadman
tadman

Reputation: 211740

If you want to compare characters, compare characters:

 if (time[8] == 'A')

Remember that in C++ 'A' is a character and "A" is a C string.

Upvotes: 5

Related Questions