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
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
