CPN
Computational Process Networks
Functions
ToString.h File Reference

A general ToStream function that takes printf like arguments and returns a std::string. More...

#include <cpn/common.h>
#include <string>
+ Include dependency graph for ToString.h:
+ This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

std::string ToString (const char *fmt,...)
 

Detailed Description

A general ToStream function that takes printf like arguments and returns a std::string.

Author
John Bridgman

Definition in file ToString.h.

Function Documentation

std::string ToString ( const char *  fmt,
  ... 
)

Takes arguments like printf and returns a std::string.

Parameters
fmtformat string like printf
Returns
an std::string result

Definition at line 31 of file ToString.cc.

32 {
33  /* Guess we need no more than 100 bytes. */
34  int n, size = 100;
35  char *p, *np;
36  va_list ap;
37  std::string ret = "";
38  p = (char*)malloc(size);
39  if (p == NULL) {
40  return ret;
41  }
42 
43  while (1) {
44  /* Try to print in the allocated space. */
45  va_start(ap, fmt);
46  n = vsnprintf(p, size, fmt, ap);
47  va_end(ap);
48  /* If that worked, return the string. */
49  if (n > -1 && n < size) {
50  ret = p;
51  free(p);
52  return ret;
53  }
54  /* Else try again with more space. */
55  if (n > -1) {
56  /* glibc 2.1 */
57  size = n+1; /* precisely what is needed */
58  }
59  else { /* glibc 2.0 */
60  size *= 2; /* twice the old size */
61  }
62  np = (char*)realloc (p, size);
63  if (np == NULL) {
64  free(p);
65  return ret;
66  } else {
67  p = np;
68  }
69  }
70 }