Search code examples
c++classprivatememberstrcmp

C++ Using strcmp() in Class on Private Member Data


I'm doing an assignment for class and am having problems compiling this code. I have used #include <string> in both the main .cpp file and the class .cpp file. The error is "‘strcmp’ is not a member of ‘std’" but I get it whether I use std::strcmp() or strcmp().

Any thoughts on what I am doing wrong?

double temporary::manipulate()
{
    if(!std::strcmp(description, "rectangle"))
    {
    cout << "Strings compare the same." << endl;
        return first * second;
    }
    return -1;
}

Solution

  • You need to include <string.h> or <cstring> for strcmp or std::strcmp respectively. <string> is a C++ standard library required for std:string and other related functions.

    Note that std::strcmp expects two const char*, not an std::string. If description is an std::string, you can get a pointer to the underlying data with the c_str() method:

    if(!std::strcmp(description.c_str(), "rectangle"))
    

    or just use the comparison operator. This is the more idiomatic solution:

    if(description == "rectangle")