C# C++ 中的 String.Format 替代方案

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10410023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:44:09  来源:igfitidea点击:

String.Format alternative in C++

c#c++stringstring-formatting

提问by user1240679

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.

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

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

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

By generating such an above string, I should be able to pass this in system(). However, systemonly accepts char*

通过生成上面这样的字符串,我应该能够将它传入system(). 不过system只接受char*

I am on Win32 C++(not C++/CLI), and cannot use boostsince 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 sprintfdoes not accept stringas the a, band cparameters. Any suggestions how I can generate these formatted strings to pass to system in my program?

我正在使用Win32 C++(不是 C++/CLI),并且无法使用,boost因为它会包含太多包含本身非常小的项目的所有文件。类似的东西sprintf()对我来说看起来很有用,但sprintf不接受string作为a,bc参数。我有什么建议可以生成这些格式化的字符串以在我的程序中传递给系统吗?

采纳答案by Luchian Grigore

You can use sprintfin combination with std::string.c_str().

您可以sprintfstd::string.c_str().

c_str()returns a const char*and works with sprintf:

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;

or you can use a pre-allocated chararray if you know the size:

或者,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() );

回答by dirkgently

The C++ way would be to use a std::stringstreamobject as:

C++ 方法是将std::stringstream对象用作:

std::stringstream fmt;
fmt << a << " " << b << " > " << c;

The C way would be to use sprintf.

C 方法是使用sprintf.

The C way is difficult to get right since:

C 方法很难正确,因为:

  • It is type unsafe
  • Requires buffer management
  • 这是类型不安全的
  • 需要缓冲区管理

Of course, you may want to fall back on the C way if performance is an issue (imagine you are creating fixed-size million little stringstreamobjects and then throwing them away).

当然,如果性能是一个问题,您可能希望退回到 C 方式(假设您正在创建固定大小的百万小stringstream对象,然后将它们扔掉)。

回答by Shep

For completeness, the boost way would be to use boost::format

为了完整起见,提升方式是使用 boost::format

cout << boost::format("%s %s > %s") % a % b % c;

Take your pick. The boost solution has the advantage of type safety with the sprintfformat (for those who find the <<syntax a bit clunky).

随你挑。boost 解决方案在sprintf格式方面具有类型安全的优势(对于那些觉得<<语法有点笨拙的人)。

回答by moooeeeep

For the sake of completeness, you may use std::stringstream:

为了完整起见,您可以使用std::stringstream

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string a = "a", b = "b", c = "c";
    // apply formatting
    std::stringstream s;
    s << a << " " << b << " > " << c;
    // assign to std::string
    std::string str = s.str();
    std::cout << str << "\n";
}


Or (in this case) std::string's very own string concatenation capabilities:

或者(在这种情况下)std::string自己的字符串连接功能:

#include <iostream>
#include <string>

int main() {
    std::string a = "a", b = "b", c = "c";
    std::string str = a + " " + b + " > " + c;
    std::cout << str << "\n";
}

For reference:

以供参考:



If you really want to go the C way. Here you are:

如果你真的想走C方式。这个给你:

#include <iostream>
#include <string>
#include <vector>
#include <cstdio>

int main() {
    std::string a = "a", b = "b", c = "c";
    const char fmt[] = "%s %s > %s";
    // use std::vector for memory management (to avoid memory leaks)
    std::vector<char>::size_type size = 256;
    std::vector<char> buf;
    do {
        // use snprintf instead of sprintf (to avoid buffer overflows)
        // snprintf returns the required size (without terminating null)
        // if buffer is too small initially: loop should run at most twice
        buf.resize(size+1);
        size = std::snprintf(
                &buf[0], buf.size(),
                fmt, a.c_str(), b.c_str(), c.c_str());
    } while (size+1 > buf.size());
    // assign to std::string
    std::string str = &buf[0];
    std::cout << str << "\n";
}

For reference:

以供参考:



Then, there's the Boost Format Library. For the sake of your example:

然后是Boost Format Library。为了你的例子:

#include <iostream>
#include <string>
#include <boost/format.hpp>

int main() {
    std::string a = "a", b = "b", c = "c";
    // apply format
    boost::format fmt = boost::format("%s %s > %s") % a % b % c; 
    // assign to std::string
    std::string str = fmt.str();
    std::cout << str << "\n";
}

回答by user1359278

As already mentioned the C++ way is using stringstreams.

如前所述,C++ 方式是使用字符串流。

#include <sstream>

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

std::stringstream ostr;
ostr << a << " " << b << " > " << c;

Note that you can get the C string from the string stream object like so.

请注意,您可以像这样从字符串流对象中获取 C 字符串。

std::string formatted_string = ostr.str();
const char* c_str = formatted_string.c_str();

回答by Bo Persson

You can just concatenate the strings and build a command line.

您可以连接字符串并构建命令行。

std::string command = a + ' ' + b + " > " + c;
system(command.c_str());

You don't need any extra libraries for this.

为此,您不需要任何额外的库。

回答by vitaut

In addition to options suggested by others I can recommend the fmt librarywhich implements string formatting similar to str.formatin Python and String.Formatin C#. Here's an example:

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

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);

Disclaimer: I'm the author of this library.

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