简体   繁体   English

如何将字符串传输到char *(不是const char *)

[英]How can I transfer string to char* (not const char*)

I wanna do something like: 我想做类似的事情:

string result;
char* a[100];
a[0]=result;

it seems that result.c_str() has to be const char*. 似乎result.c_str()必须是const char *。 Is there any way to do this? 有什么办法吗?

You can take the address of the first character in the string. 您可以获取字符串中第一个字符的地址。

a[0] = &result[0];

This is guaranteed to work in C++11. 保证可以在C ++ 11中工作。 (The internal string representation must be contiguous and null-terminated like a C-style string) (内部字符串表示形式必须像C风格的字符串一样连续且以null终止)

In C++03 these guarantees do not exist, but all common implementations will work. 在C ++ 03中,这些保证不存在,但是所有常见的实现都可以使用。

string result;
char a[100] = {0};
strncpy(a, result.c_str(), sizeof(a) - 1);

There is a member function (method) called "copy" to have this done. 有一个称为“复制”的成员函数(方法)可以完成此任务。

but you need create the buffer first. 但您需要先创建缓冲区。

like this 像这样

string result;
char* a[100];
a[0] = new char[result.length() + 1];
result.copy(a[0], result.length(), 0);
a[0][result.length()] = '\0';

(references: http://www.cplusplus.com/reference/string/basic_string/copy/ ) (参考: http : //www.cplusplus.com/reference/string/basic_string/copy/

by the way, I wonder if you means 顺便说一句,我想知道你是否意味着

string result;
char a[100];

You can do: 你可以做:

char a[100];
::strncpy(a, result.c_str(), 100);

Be careful of null termination. 注意零终止。

The old fashioned way: 老式的方式:

#include <string.h>

a[0] = strdup(result.c_str());  // allocates memory for a new string and copies it over
[...]
free(a[0]);  // don't forget this or you leak memory!

If you really, truly can't avoid doing this, you shouldn't throw away all that C++ offers, and descend to using raw arrays and horrible functions like strncpy . 如果您确实无法避免这样做,则不应抛弃C ++提供的所有功能,而应该使用原始数组和可怕的函数(例如strncpy

One reasonable possibility would be to copy the data from the string to a vector: 一种合理的可能性是将数据从字符串复制到向量:

char const *temp = result.c_str();
std::vector<char> a(temp, temp+result.size()+1);

You can usually leave the data in the string though -- if you need a non-const pointer to the string's data, you can use &result[0] . 不过,通常您可以将数据保留在字符串中-如果需要指向字符串数据的非常量指针,则可以使用&result[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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