调用函数时在c++中格式化字符串

Format string in C++ when calling function

本文关键字:格式化 字符串 c++ 函数 调用      更新时间:2023-10-16

在c#中我们可以使用:

function_name("This is test number: " + i);

如何在c++中实现?

谢谢大家

假设function_name接受std::string参数,并且您有c++ 11支持,您可以使用

function_name("This is test number: " + std::to_string(i));

首先考虑表达式

"This is test number: " + i

您想要获得一个包含操作符+的两个操作数的新字符串。所以这个字符串必须在内存中动态分配。唯一一个为字符串动态分配内存的标准c++类是std::string。然而,它没有operator +,其中一个操作数是整型的。因此对象i必须显式地转换为std::string类型的对象。它可以使用标准函数std::to_string来完成。在这种情况下,调用将看起来像

function_name("This is test number: " + std::to_string( i ) );

然而,如果函数只接受char *类型的参数,那么你就不能使用std::string类。

那你需要什么?

正如我提到的,你必须在调用函数之前分配字符数组本身。假设您定义了这样一个数组,它可以容纳字符串字面值和存储在i中的数字。

char s[SOME_ENOUGH_SIZE];

当你可以写

std::sprintf( s, "&s %i", "This is test number: ", i );
function_name( s );

还可以动态分配数组。例如

char *s = new char[SOME_ENOUGH_SIZE];

实际上,如果i是一个整数,那么string + i将产生一个移动了那么多元素的数组(假设这保持了基址在边界内,否则会产生垃圾数据)。

所以,在你的情况下,如果i=4,那么你的字符串被传递为" is test number: ",删除"This"

所以,如果你想连接字符串,你可以使用上面的解决方案:std::string:

function_name("This is test number: " + std::to_string(i));

EDIT:因为您已经评论了i不是int,所以这可能不再有效