Search code examples
c++stringcomparisonstring-comparisonstrcmp

Problems with the comparison of two strings using strcmp


I want to compare 2 string but when I do a strcmp function, it tells me that:

'strcmp' : cannot convert parameter 1 from 'std::string'

How can I fix this?

Here is my code :

int verif_file(void)
{
    string ligne;
    string ligne_or;

    ifstream verif("rasphone");
    ifstream original("rasphone.pbk");
    while (strcmp(ligne, "[SynCommunity]") != 0 &&
        (getline(verif, ligne) && getline(original, ligne_or)));    
    while (getline(verif, ligne) && getline(original, ligne_or))
    {
        if (strcmp(ligne, ligne_or) != 0)
            return (-1);
    }

    return (0);
}

Solution

  • Your compiler gives you an error because strcmp is a C-style function that expects arguments of type const char* and there is no implicit conversion from std::string to const char*.

    And although you might retrieve a pointer of this type using std::string's c_str() method, since you are working with std::string objects, you should use the operator == instead:

    if (ligne == ligne_or) ...
    

    or comparison with const char*:

    if (ligne == "[Syn****]") ...