ADMB Documentation  11.5.3197
 All Classes Files Functions Variables Typedefs Friends Defines
string2.cpp
Go to the documentation of this file.
00001 /*
00002  * $Id$
00003  *
00004  * Author: David Fournier
00005  * Copyright (c) 2008-2012 Regents of the University of California
00006  */
00007 #include <fvar.hpp>
00008 #include <string.h>
00009 #include <stdlib.h>
00010 
00011 #ifndef OPT_LIB
00012   #include <cassert>
00013 #endif
00014 
00015 adstring::adstring(const size_t lb, const size_t ub) : clist()
00016 {
00017   if (lb != 1)
00018   {
00019     cerr << " Error in adstring::adstring(int lb,int ub) : clist()\n"
00020     " At present minimum index for adstring must equal 1\n";
00021     exit(1);
00022   }
00023   size_t sz = ub;
00024   allocate(sz);
00025   for (size_t i = 1; i <= sz; i++)
00026   {
00027     s[i] = '\0'; //' ';
00028   }
00029   s[sz + 1] = '\0';
00030 }
00031 adstring::adstring(const int sz) : clist()
00032 {
00033   if (sz < 1)
00034   {
00035     cerr << " Error in adstring::adstring(const size_t size) : clist()\n"
00036     " At present size must be greater than zero.\n";
00037     exit(1);
00038   }
00039   size_t size = sz > 0 ? (size_t)sz : 0;
00040   allocate(size);
00041   for (size_t i = 1; i <= size; i++)
00042   {
00043     s[i] = '\0'; //' ';
00044   }
00045   s[size + 1] = '\0';
00046 }
00047 
00048 adstring::adstring(const char ub) : clist()
00049 {
00050   size_t sz = 1;
00051   allocate(sz);
00052 
00053   s[1] = (unsigned char)ub;
00054   s[2] = '\0';
00055 }
00056 
00057 adstring::adstring(const unsigned char ub) : clist()
00058 {
00059   size_t sz = 1;
00060   allocate(sz);
00061 
00062   s[1] = ub;
00063   s[2] = '\0';
00064 }
00065 
00066 adstring::adstring(const adstring & v) : clist(v)
00067 {
00068   shape = v.shape;
00069   s = v.s;
00070 }
00071 
00072 adstring operator+(const adstring& u, const adstring& v)
00073 {
00074   size_t us = u.size();
00075   size_t vs = v.size();
00076   adstring tmp(1, us + vs);
00077   for (size_t i = 1; i <= us; i++)
00078   {
00079     tmp(i) = u(i);
00080   }
00081   for (size_t i = 1; i <= vs; i++)
00082   {
00083     tmp(i + us) = v(i);
00084   }
00085   return tmp;
00086 }
00087 
00088 adstring itoa(int n, int r)
00089 {
00090 #ifndef OPT_LIB
00091   assert(r != 0);
00092   assert(r != 1);
00093 #endif
00094 
00095   bool sign = n < 0 ? true : false;
00096   if (sign) n *= -1;
00097   unsigned char buf[50];
00098   memset(&buf[0], ' ', 50);
00099   size_t ii=0;
00100   do
00101   {
00102     int nr = n % r;
00103     if (nr < 0) nr *= -1;
00104     buf[ii++] = (unsigned char)nr;
00105   } while (n /= r);
00106   if (sign)
00107   {
00108     ii++;
00109   }
00110   adstring s(1, ii);
00111   for (size_t i=0;i<ii;i++)
00112   {
00113     s[ii-i]=(unsigned char)(buf[i]+48);
00114   }
00115   if (sign)
00116   {
00117     s(1) = '-';
00118   }
00119   return s;
00120 }