C++ 将 const char * 转换为 std::string
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24127946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a const char * to std::string
提问by Justin Fletcher
I've got a const char *
returned from a processing function, and I'd like to convert/assign it to an instance of std::string
for further manipulation. This seems like it should be straight-forward, but I've not been able to find any documentation showing how it should be done. Obviously, I'm missing something. Insights appreciated.
我有const char *
一个处理函数的返回值,我想将它转换/分配给一个实例以std::string
进行进一步操作。这似乎应该是直截了当的,但是我找不到任何说明应该如何完成的文档。显然,我错过了一些东西。见解赞赏。
回答by Ivaylo Strandjev
std::string
has a constructor fromconst char *
.This means that it is legal to write:
std::string
有一个来自 的构造函数const char *
。这意味着这样写是合法的:
const char* str="hello";
std::string s = str;
回答by Ed Heal
Try
尝试
const char * s = "hello";
std::string str(s);
will do the trick.
会做的伎俩。
回答by Fred Larson
std::string
has a constructor that converts const char*
implicitly. In most cases, you need to do nothing. Just pass a const char*
where a std::string
is accepted and it will work.
std::string
有一个const char*
隐式转换的构造函数。在大多数情况下,您什么都不用做。只需通过一个const char*
其中一个std::string
被接受,它会工作。
回答by Vlad from Moscow
There are three possibilities. You can use a constructor, an assignment operator or member function assign
(if do not take into account member function insert
though it is also can be used:) )`
有三种可能。您可以使用构造函数、赋值运算符或成员函数assign
(如果不考虑成员函数,insert
尽管它也可以使用:))`
For example
例如
#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;
}
回答by Appleshell
You've got a lot of options:
你有很多选择:
const char* dosth() { return "hey"; }
string s1 = dosth();
string s2 (dosth());
string s3 {dosth()};
auto s4 = (string)dosth();
Note that s3
and s4
are C++11 features, if you should still work with an old or non-compliant compiler you would have to work with one of the other options.
请注意,s3
和s4
是 C++11 功能,如果您仍应使用旧的或不兼容的编译器,则必须使用其他选项之一。