首页 > 解决方案 > 如何测试字符串字符是否等于字符

问题描述

我允许用户插入一个time包含时间的字符串。格式的一个示例是 08:10:45AM。我正在测试第 8 个字符是“A”还是“P”。

这是我的代码:

#include <iostream>
#include <sstream>

using namespace std;

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

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

    return 0;
}

但是,我收到此错误:“指针和整数之间的比较('int' 和 'const char *”

有谁知道如何解决这一问题?

任何帮助将不胜感激 :)

标签: c++

解决方案


如果要比较字符,请比较字符:

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

请记住,在 C++'A'中是一个字符并且"A"是一个 C 字符串。


推荐阅读