Kac*_*per 5 c++ string string-interpolation
我习惯于在 c# 或 JavaScript 中像这样的字符串插值的易于阅读的语法,所以当我开始学习 c++ 时,我期望它会有类似的功能,但是在 c++ 中搜索字符串插值时我找不到类似的东西。
在 c# 中,字符串是这样插入的:
$"My variable has value {myVariable}"
Run Code Online (Sandbox Code Playgroud)
在 JavaScript 中,它看起来像这样:
`My variable has value ${myVariable}`
Run Code Online (Sandbox Code Playgroud)
在字符串文字的不同位置插入多个值是一个常见问题,我确信在 C++ 中有一些标准方法可以做到这一点。我想知道在 C++ 中最简单的方法是什么,人们通常是怎么做的。
从 c++20 开始,您可以使用<format>标头执行以下操作:
auto s = std::format("My variable has value {}", myVariable);
Run Code Online (Sandbox Code Playgroud)
这与 C# 或 JavaScript 中的完成方式非常相似。
FWIW,这是一个 C++11 安全版本,sprintf返回一个std::string
template<typename... Args>
std::string Sprintf(const char *fmt, Args... args)
{
const size_t n = snprintf(nullptr, 0, fmt, args...);
std::vector<char> buf(n+1);
snprintf(buf.data(), n+1, fmt, args...);
return std::string(buf.data());
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
float var = 0.123f;
std::string str = Sprintf("My variable has value %0.4f\n", var);
Run Code Online (Sandbox Code Playgroud)
如果您使用 C++20,我喜欢 @cigien 的答案。
| 归档时间: |
|
| 查看次数: |
1538 次 |
| 最近记录: |