【问题标题】:c++ add variable value to string in one linec ++在一行中将变量值添加到字符串
【发布时间】:2019-11-22 15:51:36
【问题描述】:

是否可以“轻松”将变量添加到 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++ 不能这样工作。
  • 字符串插值就是它通常所说的。 C++20 将获得一个格式库,其工作方式与std::printf 类似,但适用于字符串。
  • @Hubert 它不兼容 C++20,因为 C++20 标准还没有最终确定。该支持是针对当前 C++20 草案的实验性支持。这就是为什么命令行选项显示-std=c++2a,而不是-std=c++20
  • 。根据this,GCC 的 libstdc++ 还不支持 c++2a 文本格式。
  • @Hubert 如您所见here,尚无任何标准库支持 C++20 的文本格式添加。 (在页面上搜索“文本格式”)

标签: c++ string exception std


【解决方案1】:

有多种选择。

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

【讨论】:

  • 没有std::string_literals也可以编译
  • @SlavasupportsMonica 我明白你的意思,但我喜欢直言不讳,特别是因为char[] 是一种讨厌的类型,你可以做一些不需要的事情,比如"asdf" + 24
【解决方案2】:

你可以看看标准库提供的stringstream STL 类。对于您的示例,它将是这样的:

#include <sstream>      // std::stringstream

std::stringstream ss;

ss << i << " is incorrect";
throw std::logic_error(ss.str());

【讨论】:

  • 我不会把这称为一行
  • 公平点哈哈,但它可能比字符串连接更通用:)
猜你喜欢
  • 2017-04-03
  • 1970-01-01
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 2012-02-23
  • 1970-01-01
相关资源
最近更新 更多