-2

I am trying to convert III stored in string s in Roman numerals to 3. Here is a code snippet:

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;         

I am facing issues with using the strcmp() function. How can I use it successfully?

Here is the error:

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)
           ^
Lundin
  • 195,001
  • 40
  • 254
  • 396
bimbi
  • 70
  • 10
  • 2
    Usage of `s.size()` indicates this is not `C`. Tag the language that you're using. Also as an aside, this: `IIIIIIIIIIIIIIIIIIIII` is not a valid Roman numeral, but your program will process it as if it is one. – PaulMcKenzie Jun 23 '21 at 02:14
  • 1
    `s[i] == 'I'` ... you're comparing characters, not c strings. – ChrisMM Jun 23 '21 at 02:14

2 Answers2

2

You are comparing s[i] of type char(not a string) with "I" of type const char*(is string).

In this case, you just need to compare s[i] == 'I'

toan
  • 31
  • 4
0

Since you're using s.size(), it seems s is std::string and s[i] would be a character at index i. It's not a char* so obviously you can't compare that with "I" which is a const char[2]. To compare characters you do that directly: s[i] == 'I'

If you really want to do a string compare then you must get a const char* from s:

if (strncmp(s.c_str() + i, "I", 1) == 0){
phuclv
  • 37,963
  • 15
  • 156
  • 475