strcmp cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘const char* [duplicate]
Asked Answered
T

1

8

Apologies in advance for the elementary nature of the question.

I am trying to use the strcmp function to test two strings for matching characters.

I reduced the issue to the simple code below:

#include <iostream>
#include <cstring> 

using namespace std;

void compareStrings(string, string);

int main()
{
    string string1 = "testString", string2 = "testString";
    compareStrings(string1, string2);
    return 0;
}

void compareStrings(string stringOne, string stringTwo)
{
    if (strcmp(stringOne,stringTwo) == 0)
        cout << "The strings match." << endl;
    else 
        cout << "The strings don't match." << endl;
}

Could someone explain the following compiler error message?

./newProgram.cpp: In function ‘void compareStrings(std::string, std::string)’:
./newProgram.cpp:17:32: error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘const char*’ for argument ‘1’ to ‘int strcmp(const char*, const char*)’
  if (strcmp(stringOne,stringTwo) == 0)
                                ^

Thanks! Xz.

Typeface answered 24/5, 2014 at 19:5 Comment(1)
Why are you using strcmp with C++ strings?Jerid
N
12

strcmp is for C strings (null-terminated char *). string::compare is for C++ strings.

If you really want to use strcmp with your std::string, you can use string::c_str() to get a pointer to the underlying C-string:

if (strcmp(stringOne.c_str(), stringTwo.c_str()) == 0)

But of course, if you're using C++, you should actually use C++, and make use of std::string's == overload.

if (stringOne == stringTwo)
Nourishment answered 24/5, 2014 at 19:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.