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

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

以下两种方法:

1、使用sprintf 标准方法

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

sprintftest.cc

#include

#include

#include

#include

#include

#include

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

你可能感兴趣的:(c++,开发语言)