我从处理函数返回const char *
,我想将其转换/分配给std::string
的实例以进行进一步操作。这似乎应该是直截了当的,但我找不到任何文档说明应该如何完成。显然,我错过了一些东西。见解表示赞赏。
答案 0 :(得分:24)
std::string
有一个来自const char *
的构造函数。这意味着它是合法的:
const char* str="hello";
std::string s = str;
答案 1 :(得分:8)
尝试
const char * s = "hello";
std::string str(s);
会做到这一点。
答案 2 :(得分:2)
std::string
有一个隐式转换const char*
的构造函数。在大多数情况下,您无需做任何事情。只需传递一个const char*
,其中std::string
被接受即可。
答案 3 :(得分:1)
有三种可能性。您可以使用构造函数,赋值运算符或成员函数assign
(如果不考虑成员函数insert
,尽管它也可以使用:))`
例如
#include <iostream>
#include <string>
const char * f() { return "Hello Fletch"; }
int main()
{
std::string s1 = f();
std::string s2;
s2 = f();
std::string s3;
s3.assign( f() );
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
std::cout << s3 << std::endl;
}
答案 4 :(得分:1)
你有很多选择:
const char* dosth() { return "hey"; }
string s1 = dosth();
string s2 (dosth());
string s3 {dosth()};
auto s4 = (string)dosth();
请注意s3
和s4
是C ++ 11的功能,如果您仍然使用旧的或不兼容的编译器,则必须使用其他选项之一。