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 的首选转换
基础教程推荐
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
