从char(非char *)到std :: string的首选转换 [英] Preferred conversion from char (not char*) to std::string
问题描述
我有一个 char
,一个简单的老字符,我想变成 std :: string
。 std :: string(char)
当然不存在。我可以创建一个字符数组并复制它,我可以通过字符串流,或许多其他小迂回路由。目前,我更喜欢 boost :: lexical_cast
,但是对于这个简单的任务似乎太冗长了。那么,首选方法是什么?
I have a char
, a plain old character, that I would like to turn into an std::string
. std::string(char)
doesn't exist of course. I could create an char array and copy it in, I could go through string streams, or many other little roundabout routes. Currently, I prefer boost::lexical_cast
, but even that seems too verbose for this simple task. So what's the preferred way?
推荐答案
std :: string
构造函数,它接受一个数字和一个字符。字符将重复给定的次数。因此,您应该使用:
std::string
has a constructor that takes a number and a character. The character will repeat for the given number of times. Thus, you should use:
std::string str(1, ch);
这篇关于从char(非char *)到std :: string的首选转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!