覆盖标准::字符串到字符 *
Coverting std::String to char *
我需要将字符串传递到仅接受字符*的套接字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;
}
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数