【问题标题】:Best way to format string in C++ [duplicate]在 C++ 中格式化字符串的最佳方法 [重复]
【发布时间】:2020-10-08 20:23:04
【问题描述】:

javascript 中,我可以使用template string 格式化字符串

const cnt = 12;
console.log(`Total count: ${cnt}`);

如果我使用python,我可以使用f-string

age = 4 * 10
f'My age is {age}'

但是,如果我与 C++(17) 合作,那么最好的解决方案是什么(如果可能的话)?

【问题讨论】:

  • 安装libfmt,然后就可以fmt::print("Total count: {}", cnt);了。
  • std::cout << "Total count: " << cnt << std::endl; 也适用于字符串流
  • 我不知道是什么问题。但是如果你想在字符串中使用数字,这里就是一个例子。 size_t age = 40; std::string str = "My age is "+ std::to_string(age);

标签: c++ string c++17


【解决方案1】:

你可以使用sprintf

sprintf(dest_string, "My age is %d", age).

但是使用 sprintf 会报错,所以最好使用 snprintf:

snprintf(dest_string, size , "My age is %d", age);

其中size 是最大字节数。

【讨论】:

  • 欢迎来到 StackOverflow David。不幸的是,“C”中标记为 C++ 的问题的答案虽然有效,但往往会被否决。 (免责声明:我没有投反对票,但我也是这种文化的受害者)
  • 虽然这个解决方案可以在 C++ 中工作,但它是基于 C 的,对于 C++ 来说不是一个好的解决方案,因为它缺乏足够的类型检查和缓冲区溢出检查, C++ 已经用其他解决方案解决了。
【解决方案2】:

我认为更简单的方法是std::to_string:

std::string str = "My age is ";
str += std::to_string(age);

std::ostringstream 也很好用,也很有用:

在你的源文件的顶部有这个

#include <sstream>

然后在代码中,你可以这样做:

std::ostringstream ss;
ss << "My age is " << age;
std::string str = ss.str();

【讨论】:

    【解决方案3】:

    如果你想写入标准输出:

    const int cnt = 12;
    std::cout << "Total count: " << cnt << "\n";
    

    写入任何其他流的工作方式类似。例如,将 std::cout 替换为 std::ofstream 以写入文件。如果需要格式化字符串:

    std::ostringstream oss;
    oss << "Total count: " << cnt << "\n";
    std::string s = oss.str();
    std::cout << s;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-29
      • 2012-07-09
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 2018-08-10
      • 1970-01-01
      相关资源
      最近更新 更多