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.
这篇关于连接普通字符和字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:连接普通字符和字符串?


基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01