C 中的 String.Format 替代方案

新手上路,请多包涵

我没有太多使用 C++ 的经验。相反,我在 C# 中工作得更多,因此,我想通过与我将在那里做的事情相关联来问我的问题。我必须生成特定格式的字符串,我必须将其传递给另一个函数。在 C# 中,我可以通过下面的简单代码轻松生成字符串。

 string a = "test";
string b = "text.txt";
string c = "text1.txt";

String.Format("{0} {1} > {2}", a, b, c);

通过生成上述这样的字符串,我应该能够在 system() 中传递它。但是, system 只接受 char*

我在 Win32 C++ (不是 C++/CLI)上,并且不能使用 boost 因为它会包含太多的项目本身很小的所有文件。 Something like sprintf() looks useful to me, but sprintf does not accept string as the a , b and c 参数。有什么建议可以在我的程序中生成这些格式化的字符串以传递给系统吗?

原文由 user1240679 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 686
2 个回答

您可以将 sprintfstd::string.c_str() 结合使用。

c_str() 返回一个 const char* 并与 sprintf 一起使用:

 string a = "test";
string b = "text.txt";
string c = "text1.txt";
char* x = new char[a.length() + b.length() + c.length() + 32];

sprintf(x, "%s %s > %s", a.c_str(), b.c_str(), c.c_str() );

string str = x;
delete[] x;

或者,如果您知道大小,您可以使用预先分配的 char 数组:

 string a = "test";
string b = "text.txt";
string c = "text1.txt";
char x[256];

sprintf(x, "%s %s > %s", a.c_str(), b.c_str(), c.c_str() );

原文由 Luchian Grigore 发布,翻译遵循 CC BY-SA 3.0 许可协议

除了其他人建议的选项之外,我还可以推荐 fmt 库,它实现了类似于 Python 中的 String.Format 和 C# 中的 str.format 的字符串格式。这是一个例子:

 std::string a = "test";
std::string b = "text.txt";
std::string c = "text1.txt";
std::string result = fmt::format("{0} {1} > {2}", a, b, c);

免责声明:我是这个库的作者。

原文由 vitaut 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题