String.Format在C ++中的替代 [英] String.Format alternative in C++
问题描述
我没有太多使用C ++的经验。相反我在C#中工作更多,所以,我想问我的问题,关于我会在那里做什么。我必须生成一个特定的字符串格式,我必须传递给另一个函数。在C#中,我很容易通过下面的简单代码生成字符串。
I don't have much experience working with C++. Rather I have worked more in C# and so, I wanted to ask my question by relating to what I would have done in there. I have to generate a specific format of the string, which I have to pass to another function. In C#, I would have easily generated the string through the below simple code.
string a = "test";
string b = "text.txt";
string c = "text1.txt";
String.Format("{0} {1} > {2}", a, b, c);
通过生成这样一个上面的字符串,我应该能够在 system()
。但是,系统
接受char *
By generating such an above string, I should be able to pass this in system()
. However, system
accepts on char*
我在 Win32 C ++
(不是C ++ / CLI),并且不能使用 boost
,因为它会包含太多的项目的所有文件,它本身很小。像 sprintf()
似乎对我有用,但 sprintf
不接受 string
为
a
, b
和 c
参数。任何建议我如何可以生成这些格式化的字符串传递到我的程序中的系统?
I am on Win32 C++
(not C++/CLI), and cannot use boost
since it would include too much inclusion of all the files for a project which itself is very small. Something like sprintf()
looks useful to me, but sprintf
does not accept string
as the a
, b
and c
parameters. Any suggestions how I can generate these formatted string to pass to system in my program?
推荐答案
可以使用 sprintf
结合 std :: string.c_str()
。
code> c_str()返回 const char *
并与 sprintf
:
c_str()
returns a const char*
and works with 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
array如果你知道大小:
or you can use a pre-allocated char
array if you know the size:
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() );
这篇关于String.Format在C ++中的替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!