LINUX.ORG.RU

sprintf(stroka, "%d", chislo);

anonymous
()

Все будут смеяться, но я делаю так.

Объявляю где-нибудь:

template <class T>
inline std::string to_str(T arg)
{
    std::ostringstream buf;
    buf << arg;
    return buf.str();
}

А в программе вызываю:

std::string s = to_str(12345);

Если нужен char[], то:

char *ss = s.c_str();

hbee ★★★★
()
Ответ на: комментарий от Titanicum

Вы сошли с ума, сэр! strtol переводит строку в int. Сабж sprintf.

anonymous
()

Хм, интересная это библиотека boost... Будущий стандарт?

std::string s = lexical_cast<std::string>(12345);

hbee ★★★★
()

О, выцарапал шуструю процедурину:

static char integers[10]={'0','1','2','3','4','5','6','7','8','9'};
      
/*converts long to a string representation and returns it:*/
char *long2str(char *buf, long n)
{
char tmp[21];/* This is a stack. 64/Log_2[10] = 19.3, so this is enough forever...*/
register char *bufptr=buf, *tmpptr=tmp+1;/*tmp[0] is a terminator ('\0')*/

   if(n<0){/*Swap the sign and store '-':*/
      n=-n;
      *bufptr++='-';
   }/*if(n<0)*/
                
   *tmp='\0';/*Set terminator*/
             
   /*Fill up the stack:*/
   do
     *tmpptr++=integers[n%10];
   while( (n=n/10)!=0 );
 
   /*Copy the stack to the output buffer:*/
   while( (*bufptr++ = *--tmpptr)!='\0' );
   return buf;
}/*long2str*/

Die-Hard ★★★★★
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.