【问题标题】:C++ What should I use to save formatted in a string variable like sprintf()?C++ 我应该使用什么来保存格式化为像 sprintf() 这样的字符串变量?
【发布时间】:2018-07-28 22:36:05
【问题描述】:

我习惯用 C 编程,但现在我需要在一个项目中使用 C++,我需要将一些文本保存到一个字符串中,我在 C 中使用的代码会是

sprintf(pathFotosLimpias, "CleanPictures/Picture_T%d_%d", pictureNumber, templateNumber);

或者类似的东西,但是 pathFotosLimpias 是一个字符串,所以它不起作用,我找不到如何将它保存为一个刺痛,我认为有一个 boost 函数可以做类似于我需要的东西,但我不知道我到底应该怎么做,有人可以解释我需要什么,或者给我一个如何使用它的例子吗?

谢谢。

更新:这显然是来自 opencv 的 cv::String,我现在有点困惑。没关系,这是一个错误。

【问题讨论】:

  • 您不能真正将sprintfstd::strings 一起使用。请改用std::ostringstream
  • 响应您的编辑,我对cv::String 类型一无所知,但它可能与sprintf 的使用不兼容。如果您热衷于使用该函数,那么您需要输出为 C 风格的字符串(即 char 数组),然后将其转换为您需要的类型。但 tjis 并不完全是最优的。
  • 也许你可以使用std::stringstream之类的东西。然后,您可以使用运算符<< 在流中加载任意内容。然后调用方法str()获取字符串。
  • 我查了一下,是的,这似乎是我想要的,但我很难理解它是如何工作的。 pathFotosLimpias << "CleanPictures/Picture_T" << pictureNumber << templateNumber 应该工作吗?你有任何链接到我可以学习如何使用它的地方吗?

标签: c++ string opencv formatting printf


【解决方案1】:

您可以直接添加字符串:

#include <string> //put this at the top
auto path = std::string("CleanPictures/Picture_T") + std::to_string(pictureNumber) + "_" + std::to_string(templateNumber);

(这里"_"被隐式转换为std::string

或者使用字符串流:

#include <sstream> //put this at the top
auto stream = std::stringstream{};
stream << "CleanPictures/Picture_T" << pictureNumber << '_' << templateNumber;
auto path = stream.str(); //get the string from the stream

另一种可能性是使用abseil,它提供了printf 的类型安全替换:

auto path = absl::StrFormat("CleanPictures/Picture_T%d_%d", pictureNumber, templateNumber);

从所有这些可能性中,我会推荐:

  1. 如果您担心类型安全,请使用字符串流。
  2. 如果您想要一些性能更高的代码,请使用 std::to_string
  3. 如果您担心类型安全和性能,请使用 abseil

编辑:

生成字符串的另一种可能性是fmt 库。我现在会把它放在我推荐的顶部,因为它提供了广泛的格式化选项(使用 python 格式化样式)并且易于阅读/使用。

#include <fmt/format.h>
std::string path = fmt::format("CleanPictures/Picture_T{:d}_{:d}", pictureNumber, templateNumber);

【讨论】:

    【解决方案2】:

    您可以在 C++ 中使用 std::sprintf(),类似于在 C 中使用 sprintf()

    #include <cstdio>
    
    char pathFotosLimpias[...];
    std::sprintf(pathFotosLimpias, "CleanPictures/Picture_T%d_%d", pictureNumber, templateNumber);
    

    但是,您应该在 C++ 中使用 std::ostringstream

    #include <string>
    #include <sstream>
    
    std::ostringstream oss;
    oss << "CleanPictures/Picture_T" << pictureNumber << "_" << templateNumber;
    std::string pathFotosLimpias = oss.str();
    

    【讨论】:

      猜你喜欢
      • 2011-01-12
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多