C++ 字符串格式化的两种方法

字符串是大家常用的数据结构,经常会用的输入、输出的序列化(格式化)

以下两种方法:

1、使用sprintf 标准方法

2、使用format方法(实现格式化输入)

sprintftest.cc

#include <stdio.h>

#include <iostream>

#include <string>

#include <cstdarg>

#include <cstdio>

#include <stdlib.h>

using namespace std;

string format(const char *fmt, ...) {

  char buf[1024];       // should be enough for most cases

  int n, size = sizeof(buf);

  char *p = buf;

  va_list ap;

  do {

    va_start(ap, fmt);

    n = vsnprintf(p, size, fmt, ap);

    va_end(ap);

    if (n > -1 && n < size)

      break;    // worked!

    if (n > -1)         // glibc 2.1+/iso c99

      size = n + 1;     //   exactly what's needed

    else                // glibc 2.0

      size *= 2;        //   double the size and try again

    p = (char *)(p == buf ? malloc(size) : realloc(p, size));

    if (!p)

      throw bad_alloc();

  } while (true);

  if (buf == p)

    return string(p, n);

  string ret(p, n);

  free(p);

  return ret;

}

int main()

{

   char tmp[128]={0};

   string test="format test";

   cout << "using sprintf !!!" << endl;

   cout << "test: " << test << endl;

   sprintf(tmp,"%s|%lu|%lu",test.c_str(),1375164981000000001,1375164983000000000);

   string test2 = tmp;

   cout << "test2: " << test2 << endl;

   cout << "using format !!!" << endl;

   string test3 = format("%s|%lu|%lu",test.c_str(),1375164981000000001,1375164983000000000);

   cout << "test3: " << test3 << endl;

[jack@hyt1 Downloads]$ vim sprintftest.cc

[jack@hyt1 Downloads]$ g++ -o sprintftest sprintftest.cc 

[jack@hyt1 Downloads]$ 

[jack@hyt1 Downloads]$ ./sprintftest 

using sprintf !!!

test: format test

test2: format test|1375164981000000001|1375164983000000000

using format !!!

test3: format test|1375164981000000001|1375164983000000000

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shinobi_Jack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值