如果我将char*传递给函数.我想把那个char*转换为std :: string,一旦我得到我的结果,就从std :: string将它转换回char*来显示结果.
所以我需要做的步骤
如果可能的话,我可以看看如何通过引用vs一个指针来完成它(它的地址我通过值传入但是我仍然可以修改指针所指向的值.所以即使函数中指针地址的副本被破坏了我仍然看到外面的变化值.
谢谢!
Jam*_*lis 43
将a转换char*为std::string:
char* c = "Hello, world";
std::string s(c);
Run Code Online (Sandbox Code Playgroud)
将a转换std::string为char*:
std::string s = "Hello, world";
char* c = new char[s.length() + 1];
strcpy(c, s.c_str());
// and then later on, when you are done with the `char*`:
delete[] c;
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用std::vector<char>而不是实际char*; 那么你不必管理自己的记忆:
std::string s = "Hello, world";
std::vector<char> v(s.begin(), s.end());
v.push_back('\0'); // Make sure we are null-terminated
char* c = &v[0];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83278 次 |
| 最近记录: |