调用函数时在c++中格式化字符串
Format string in C++ when calling function
在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
,所以这可能不再有效
相关文章:
- 如何从C++中的格式化字符串派生整数?
- C++逐步格式化字符串
- 有没有更快的方法从成员函数返回格式化字符串
- 如何在提升库中格式化字符串
- 使用参数的可变大小向量格式化字符串(例如,将参数向量传递给 std::snprintf)
- 使用 c++ 格式化字符串的自然方法
- 如何在 tchar 中添加格式化字符串(用于多个文件名等)
- 需要从格式化字符串移动到二进制缓冲区
- 格式化字符串
- 用于创建格式化字符串的Variadic模板
- 使用递增的整数 C++ 格式化字符串
- 从variadic函数返回格式化字符串
- 要流式传输的格式化字符串
- 需要帮助格式化字符串输出
- 如何从格式化字符串中获取 Boost::p osix_time::p time
- 以格式化字符串的形式获取经过的时间
- 将数字转换为格式化字符串,然后再次分析格式化字符串
- 为什么在Clang中使用__attribute__((__format__(__printf_..))来避免格式化字符串
- Qt C++将秒转换为格式化字符串(hh:mm:ss)
- 基于其他变量格式化字符串