首页 > 解决方案 > 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);

标签: c++stringexceptionstd

解决方案


有几种选择。

一种是使用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)};
}

推荐阅读