使用 strcmp 在 C++ 中对常量字符串和字符串元素进行字符串比较

问题描述

我正在尝试将存储在罗马数字字符串 III 中的 s 转换为 3。这是一个代码片段:

int i = 0;
int num = 0;
while (i < s.size()){
    if (strcmp(s[i],"I") == 0){
        num = num + 1;
        i = i + 1;
    }
    else{
        continue;
    }
}

return num;         

我在使用 strcmp() 函数时遇到问题。我怎样才能成功使用它?

这里是错误

Line 18: Char 17: error: no matching function for call to 'strcmp'
            if (strcmp(s[i],"I") == 0){
                ^~~~~~
/usr/include/string.h:137:12: note: candidate function not viable: no kNown conversion 
from '__gnu_cxx::__alloc_traits<std::allocator<char>,char>::value_type' (aka 'char') to 'const char *' for 1st argument; 
take the address of the argument with &
extern int strcmp (const char *__s1,const char *__s2)
           ^

解决方法

您正在比较 why 类型的 s[i](不是字符串)与 char 类型的 "I"(是字符串)。

在这种情况下,您只需要比较 const char*

,

由于您使用的是 s.size(),因此 s 似乎是 std::string,而 s[i] 将是索引 i 处的一个字符。它不是 char*,因此显然您无法将其与 "I" 进行比较,后者是 const char[2]。要直接比较字符:s[i] == 'I'

如果您真的想进行字符串比较,那么您必须从 const char* 获取 s

if (strncmp(s.c_str() + i,"I",1) == 0){