【问题标题】:String comparison for constant string and a string element in C++ using strcmp使用 strcmp 在 C++ 中对常量字符串和字符串元素进行字符串比较
【发布时间】:2021-09-06 14:05:57
【问题描述】:

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

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)
           ^

【问题讨论】:

  • 使用s.size() 表示这不是C。标记您正在使用的语言。顺便说一句,这:IIIIIIIIIIIIIIIIIIIII 不是一个有效的罗马数字,但你的程序会像处理它一样处理它。
  • s[i] == 'I' ...您正在比较字符,而不是 c 字符串。

标签: c++ string char strcmp


【解决方案1】:

您将char(不是字符串)类型的s[i]const char*(是字符串)类型的"I" 进行比较。

在这种情况下,你只需要比较s[i] == 'I'

【讨论】:

    【解决方案2】:

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

    如果你真的想做一个字符串比较,那么你必须从s得到一个const char*

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

    【讨论】:

      猜你喜欢
      • 2011-03-20
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 2023-03-18
      相关资源
      最近更新 更多