Concatenate plain char and string?(连接普通字符和字符串?)
问题描述
我被这个看似简单的问题完全搞糊涂了.
im getting totally confused by this seemingly simple problem.
我有一个痛苦的旧字符,我想将它连接到一个字符串的中间.像这样.
I have a pain old char, and I want to concatenate it in the middle of a string. Like so.
string missingOptionArg(char missingArg) {
return "Option -" + missingArg + " requires an operand";
}
我猜 + 操作数足够聪明,可以处理这种琐碎的事情,如果不是,那么最简单的方法是什么?
I was guessing the + operand was smart enough to deal with this sort of trivial thing, if not, what would be the simplest way of doing this?
推荐答案
连接字符串字面量和字符:
To concatenate string literal and char:
std::string miString = std::string("something") + c;
当您需要连接两个字符串字面量时,也会发生类似的情况.
A similar thing happens when you need to concat two strings literals.
注意 "something"
不是 std::string
,它是一个指向字符数组的指针.然后你不能使用 + 连接两个字符串文字,那将添加两个指针并且不是你想要的.
Note that "something"
is not a std::string
, it is a pointer to an array of chars. Then you can't concatenate two string literals using +, that would be adding two pointers and is not what you want.
您的代码的更正在 Igor 的评论中.
The correction of your code is in Igor's comment.
这篇关于连接普通字符和字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:连接普通字符和字符串?


- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01