如何将char *复制到字符串中,反之亦然 [英] how to copy char * into a string and vice-versa
问题描述
如果我传递一个char *到函数。我想要然后拿这个字符*转换为一个std ::字符串,一旦我得到我的结果转换回到char *从std :: string显示结果。
If i pass a char * into a function. I want to then take that char * convert it to a std::string and once I get my result convert it back to char * from a std::string to show the result.
- 我不知道如何做这个转换(我不是说const char *只是char *)
- 我不知道如何操作我发送的指针的值。
- 接受字符
- 将其转换为字符串。
- 接受该字符串的结果并将其以char *的形式返回。
- 返回结果,以使该值应在函数之外可用,而不是被毁。
- take in a char *
- convert it into a string.
- take the result of that string and put it back in the form of a char *
- return the result such that the value should be available outside the function and not get destroyed.
如果可能,我可以看到它是如何通过引用vs指针(其地址我通过值,但我仍然可以修改指针所指向的值,所以即使函数中指针地址的副本被破坏,我仍然可以看到外部的改变值。
If possible can i see how it could be done via reference vs a pointer (whose address I pass in by value however I can still modify the value that pointer is pointing to. so even though the copy of the pointer address in the function gets destroyed i still see the changed value outside.
谢谢! p>
thanks!
推荐答案
将 char *
转换为 std: :string
:
char* c = "Hello, world";
std::string s(c);
转换 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;
我更喜欢使用 std :: vector< char>
而不是实际的 char *
;那么你不必管理自己的内存:
I prefer to use a std::vector<char>
instead of an actual char*
; then you don't have to manage your own memory:
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];
这篇关于如何将char *复制到字符串中,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!