I have a question about a char array: I have a form '"1"+lapcounter+":"+seconds' that must come in a char array. How can i fill this array in this form?
Thanks
如果您的意思是您有一些要格式化为字符串的数字变量,请为此使用字符串流:
std::stringstream ss;
ss << "1" << lapcounter << ":" << seconds";
现在您可以从中提取一个字符串:
std::string s = ss.str();
如果出于某种原因你真的想要一个字符数组(我相信你不会)
char const * cs = s.c_str();
使用sprintf
或snprintf
。此函数的工作方式类似于printf
但不是标准输出,输出将转到您指定的 char 数组。例如:
char buffer[32];
snprintf(buffer, sizeof(buffer), "1%d:%d", lapcounter, seconds);
to_string
像这样使用:
#include <iostream>
#include <string>
int main()
{
int lapcounter = 23;
std::string str("1");
str.append(std::to_string(lapcounter ));
str.append(":seconds");
std::cout << str << std::endl;
}
印刷
123:seconds
如果你真的需要一个 char 数组,你可以从ss.c_str()