c_func.hpp

Go to the documentation of this file.
00001 #ifndef GLIM_STRING_HPP_
00002 #define GLIM_STRING_HPP_
00003 
00004 /// Rare, but useful, string functions.
00005 /// @file
00006 
00007 namespace glim {
00008 
00009 /**
00010  * Copy src into dest, returing a pointer to the last updated character of the dest.
00011  * If the length of the src is bigger then len, then only the len - 1 characters are copied into the dest.
00012  * The dest is always null-terminated, therefore returning pointer always points to the terminator.
00013  */
00014 template <typename CHAR>
00015 char* stpncpy (CHAR* dest, CHAR const* src, int len) {
00016   --len;
00017   while (len > 0 && *src != 0) {*dest++ = *src++; --len;}
00018   *dest = 0;
00019   return dest;
00020 };
00021 
00022 /**
00023  * Convert an integer to a decimal string.
00024  * Returns a pointer to the end of the dest, just like stpcpy.
00025  * @bug does not work well with very big integers.
00026  */
00027 template <typename INT>
00028 char* itoa (char* dest, INT i) {
00029   if (!i) {*dest++ = '0'; *dest = 0; return dest;}
00030   bool sign; if (i < 0) {i *= -1; sign = true;} else {sign = false;}
00031   int8_t len = 0; INT z = i; while (z != 0) {++len; z /= 10;}
00032   if (sign) ++len; char* p = dest + len; *p = 0;
00033 
00034   do {*--p = (i % 10) + '0'; i /= 10;} while (i);
00035   if (sign) *--p = '-'; return dest + len;
00036 };
00037 
00038 } // namespace glim
00039 
00040 #endif // GLIM_STRING_HPP_

Generated on Fri Nov 24 20:57:37 2006 for libglim by  doxygen 1.4.6