覆盖标准::字符串到字符 *

Coverting std::String to char *

本文关键字:字符 字符串 标准 覆盖      更新时间:2023-10-16

我需要将字符串传递到仅接受字符*的套接字send()函数中。所以在这里我试图转换它:

void myFunc(std::string str)  //Taking string here const is good idea? I saw it on some examples on web
{
    char *buf = str.c_str;    //taking buf const is good idea?
    std::cout << str;
}
int main()
{
    const std::string str = "hello world";
    myFunc(str);
    return 0;
}

给出错误:

test.cpp:6:18: error: cannot convert ‘std::basic_string<_CharT, _Traits, _Alloc>::c_str<char, std::char_traits<char>, std::allocator<char> >’ from type ‘const char* (std::basic_string<char>::)()const’ to type ‘char*’

首先,c_str()是一个函数,所以你需要调用它。

其次,它返回的是const char*而不是char*

总而言之:

const char* buf = str.c_str();

首先,调用 c_str() 有一个函数。之后,c_str() 返回一个 const char*,如果你想使用 std::strcpy() 复制一个 char*:http://en.cppreference.com/w/cpp/string/byte/strcpy

尝试:

void myFunc(std::string str)
{
    const char *buf = str.c_str();
    std::cout << str;
}