C ++比较一个字符串的索引和另一个字符串?

Bre*_*ing 0 c++ string stdstring

如何比较字符串中的单个字符和另一个字符串(可能大于或小于一个字符)

这个程序给了我近300行随机错误。错误也没有引用特定的行号,只是有关“ char *”,“”或“ std :: to_string”的很多东西。

#include <iostream>
#include <string>

using std::cout;
using std::string;

int main() {
    string str = "MDCXIV";
    string test = "D";

    if (test == str[4]) {     // This line causes the problems
        cout << test << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 5

str[4]是一种char类型,不会与进行比较string

比较苹果与苹果。

使用

test[0] == str[4]
Run Code Online (Sandbox Code Playgroud)

代替。