c++ - c ++在一行中将变量值添加到字符串
问题描述
是否可以“轻松”将变量添加到 C++ 字符串?
我想要类似的行为
printf("integer %d", i);
但在字符串中,特别是在抛出这样的异常时:
int i = 0;
throw std::logic_error("value %i is incorrect");
应该与
std::string ans = "value ";
ans.append(std::atoi(i));
ans.append(" is incorrect");
throw std::logic_error(ans);
解决方案
有几种选择。
一种是使用std::to_string:
#include <string>
#include <stdexcept>
auto test(int i)
{
using namespace std::string_literals;
throw std::logic_error{"value "s + std::to_string(i) + " is incorrect"s};
}
如果您想更好地控制格式,您可以使用std::stringstream
:
#include <sstream>
#include <stdexcept>
auto test(int i)
{
std::stringstream msg;
msg << "value " << i << " is incorrect";
throw std::logic_error{msg.str()};
}
正在开发一个新的标准格式库。Afaik 它在 C++20 的轨道上。它会是这样的:
#include <format>
#include <stdexcept>
auto test(int i)
{
throw std::logic_error(std::format("value {} is incorrect", i)};
}
推荐阅读
- php - Symfony,请求找不到服务
- c# - 致命错误 C1001:编译器发生内部错误。在 gcroot.h
- python - 使用 BFS 存储从开始到结束节点的所有路径
- python - 如何根据条件暂停人脸识别并在python中执行语句/函数
- assembly - 如何禁用某些 msp430 gcc 代码注入
- php - 如何计算非空变量以获得非空的总和
- docusignapi - 如何将发件人更改为其他用户?
- azure - Azure 表单识别器 - 标签变量类型数据 - 接收列表中的数据
- javascript - 如何循环遍历对象数组以添加缺少值的对象
- amazon-web-services - 从 S3 存储桶读取火花的 AWS 收费?