C的format字符串用std::string如何实现
C里面的format格式化字符串用习惯了,是不是在纠结std::string怎么没有format了。
#include "stdio.h"
int main()
{
const char* pcServerID = "34020000002090000111";
const char* pcServerIP = "127.0.0.1";
int iServerPort = 5060;
//格式化输出到屏幕
printf("sip:%s@%s:%d\n", pcServerID, pcServerIP, iServerPort);
//format 字符串到数组
char szBuffer[512] = { 0 };
sprintf(szBuffer, "sip:%s@%s:%d\n", pcServerID, pcServerIP, iServerPort);
printf(szBuffer);
return 0;
}
用std::string如何实现同样的效果?看代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char* pcServerID = "34020000002090000111";
const char* pcServerIP = "127.0.0.1";
int iServerPort = 5060;
//定义的时候格式化
string s1 = "sip:" + string(pcServerID) + '@' + string(pcServerIP) + ':' + std::to_string(iServerPort);
string s2;
//赋值的时候格式化
s2 = "sip:" + string(pcServerID) + '@' + string(pcServerIP) + ':' + std::to_string(iServerPort);
cout << s1 << endl << s2 << endl;
return 0;
}
是不是更方便更安全,不用担心buffer的溢出!