我有这个代码:
string username;
string node;
string at;
string final;
struct passwd* user_info = getpwnam("mike");
struct utsname uts;
uname(&uts);
username = user_info->pw_name;
node = uts.nodename;
at = "@";
final = username + at +node;
i=strlen(final[0]);
char *pp = new char[i];
strcpy(pp,final);
fputs(pp, stdout);
我只想将这 3 个 strings
转换成一个 char*
。我知道我的代码完全错误,但我通过谷歌测试了很多东西。有人可以帮帮我吗?
最佳答案
您只需要使用 strings::c_str()
string final;
const char *pp = final.c_str();
如果您需要获取 char*
而不是 const char *
中的字符串数据,那么您需要按如下方式复制
:
std::string final;
//Allocate pointer large enough to hold the string data + NULL
char *pp = new char[final.size() + 1];
//Use Standard lib algorithm to copy string data to allocated buffer
std::copy(final.begin(), final.end(), pp);
//Null terminate after copying it
pp[final.size()] = '\0';
//Make use of the char *
//delete the allocated memory after use, notice delete []
delete []pp;
关于c++ - C++ 问题中的字符串转字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8961800/