Preferred conversion from char (not char*) to std::string(从 char(不是 char*)到 std::string 的首选转换)
问题描述
我有一个 char
,一个普通的旧字符,我想把它变成一个 std::string
.std::string(char)
当然不存在.我可以创建一个 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 的首选转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 char(不是 char*)到 std::string 的首选转换


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09