Geant4 Cross Reference |
1 // Copyright (C) 2010, Guy Barrand. All rights 2 // See the file tools.license for terms. 3 4 #ifndef tools_sprintf 5 #define tools_sprintf 6 7 #include <string> 8 #include "snpf" 9 10 namespace tools { 11 12 inline bool vsprintf(std::string& a_string,int 13 a_string.clear(); 14 if(a_length<0) return false; 15 if(!a_format) return false; 16 char* _s = new char[a_length+1]; 17 if(!_s) return false; 18 _s[a_length] = '\0'; 19 int n = vsnpf(_s,a_length+1,a_format,a_args) 20 if(n>a_length) { 21 delete [] _s; 22 return false; 23 } 24 if(_s[a_length]!='\0') { 25 delete [] _s; 26 return false; 27 } 28 a_string = _s; 29 delete [] _s; 30 return true; 31 } 32 33 34 inline bool sprintf(std::string& a_string,int 35 a_string.clear(); 36 if(a_length<0) return false; 37 if(!a_format) return false; 38 char* _s = new char[a_length+1]; 39 if(!_s) return false; 40 _s[a_length] = '\0'; 41 va_list args; 42 va_start(args,a_format); 43 int n = vsnpf(_s,a_length+1,a_format,args); 44 va_end(args); 45 if(n>a_length) { 46 delete [] _s; 47 return false; 48 } 49 if(_s[a_length]!='\0') { 50 delete [] _s; 51 return false; 52 } 53 a_string = _s; 54 delete [] _s; 55 return true; 56 } 57 58 inline bool print2sv(std::string& a_string,int 59 if(a_length<0) {a_string.clear();return fals 60 if(!a_format) {a_string.clear();return false 61 a_string.assign(a_length,' '); //data = a_le 62 char* _s = const_cast<char*>(a_string.c_str( 63 //_s[a_length] shoulg be '\0'. 64 int n = vsnpf(_s,a_length+1,a_format,a_args) 65 if(n>a_length) { //a_string is compromised. 66 a_string.clear(); //we cross fingers. 67 return false; 68 } 69 if(_s[a_length]!='\0') { //a_string is compr 70 a_string.clear(); //we cross fingers. 71 return false; 72 } 73 a_string.resize(n); 74 return true; 75 } 76 77 inline bool print2s(std::string& a_string,int 78 if(a_length<0) {a_string.clear();return fals 79 if(!a_format) {a_string.clear();return false 80 a_string.assign(a_length,' '); //data = a_le 81 char* _s = const_cast<char*>(a_string.c_str( 82 //_s[a_length] shoulg be '\0'. 83 va_list args; 84 va_start(args,a_format); 85 int n = vsnpf(_s,a_length+1,a_format,args); 86 va_end(args); 87 if(n>a_length) { //a_string is compromised. 88 a_string.clear(); //we cross fingers. 89 return false; 90 } 91 if(_s[a_length]!='\0') { //a_string is compr 92 a_string.clear(); //we cross fingers. 93 return false; 94 } 95 a_string.resize(n); 96 return true; 97 } 98 99 template <class MATRIX> //for example : MATRIX 100 inline void set_matrix(MATRIX& a_matrix,const 101 unsigned int DR = a_matrix.rows(); 102 unsigned int DC = a_matrix.cols(); 103 std::string ss; 104 for(unsigned int i=0;i<DR;i++) { 105 for(unsigned int j=0;j<DC;j++) { 106 tools::sprintf(ss,128,a_fmt.c_str(),i,j) 107 a_matrix.set_value(i,j,ss); 108 } 109 } 110 } 111 112 } 113 114 #endif