c++ - C++ 问题中的字符串转字符

标签 c++ string char

我有这个代码:

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/

相关文章:

android - 如何将以下代码分解为android中的各个类

Java 的字符串连接在 'for' 循环中不起作用

c - 打印并扫描字符串 c

c - C 中的 malloc 字符串

c++ - 插入数组排序法

c++ - GNU 使 : generate list of source files

c++ - NULL 指针比较失败

c++ - c++11 中 std::move 操作的行为

java - 替换字符串中的重复子串

c - C语言中char word[100]是什么意思