简体   繁体   中英

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;
}

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

#include <cstring>即可使用此功能。

Standard C functions including strcmp in C++ are declared in header <cstring> . Header <string> defines standard class std::basic_string . So you need directive

#include <cstring>

Try

#include <cstring>

...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM