C++问题中要字符的字符串

Strings to Char in C++ Issues

本文关键字:字符串 字符 问题 C++      更新时间:2023-10-16

我有这个代码:

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*。我知道我的代码完全错误,但我通过谷歌测试了很多东西。有人能帮帮我吗?

您只需要使用字符串::c_str()

string final;
const char *pp  = final.c_str();

如果你需要在char*而不是const char *中获得字符串数据,那么你需要像这样copy

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()] = ''; 
//Make use of the char *

//delete the allocated memory after use, notice delete []
delete []pp;  

为什么需要一个*char。我会把所有的东西都放进决赛。如果你需要一个*字符,你可以打电话给:

 final.c_str();

如果你想使用char。确保您保留了足够的内存:

 i=final.size()+1; 
 char *pp = new char[i];

不能直接将string转换为char*

如果const char*合适,则可以使用string::c_str()

否则,您需要将字符串的内容复制到预先分配的char数组中。