c ++在一行中将变量值添加到字符串
c++ add variable value to string in one line
是否可以"easily"向 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)};
}
你可以看看标准库提供的stringstream
STL class。对于您的示例,它将是这样的:
#include <sstream> // std::stringstream
std::stringstream ss;
ss << i << " is incorrect";
throw std::logic_error(ss.str());
是否可以"easily"向 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)};
}
你可以看看标准库提供的stringstream
STL class。对于您的示例,它将是这样的:
#include <sstream> // std::stringstream
std::stringstream ss;
ss << i << " is incorrect";
throw std::logic_error(ss.str());