Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++ Integer to String

Name: Anonymous 2008-06-07 5:44

Hi /prog/.

I am right now working on my C++ project for my programming class and I started wondering. What method's do you use to convert integer to string? There is so many of them, and most require at least 4 additional code lines. Which method do you prefer?

Name: Anonymous 2008-06-08 3:23

    const char digits[] = "0123456789";\[/code]
fixed.

>>43
[code]$ cat test_42.c
#include <stdio.h>

#define INTEGERTOSTRING(i)\
  ({\
    __typeof__(i) _i = (i), negative = _i < 0 ? 1 : 0;\
    const char digits[] = "0123456789";\
    char *str = malloc((size_t)log10(_i) + 2 + negative) + (int)log10(_i) + 1 + negative;\
    *str-- = 0;\
    for(; _i; _i /= 10) *str-- = digits[_i % 10];\
    if(negative) *str-- = '-';\
    ++str;\
  })

int main(){
 int i = 42;
 char *s = INTEGERTOSTRING(i);
 puts(s);
 free(s);
 return 0;
}
$ gcc test_42.c -o test_42 -lm
$ ./test_42
42
$ cat test_43.c
#include <stdio.h>

#define INTEGERTOSTRING(i)\
  do {\
    __typeof__(i) _i = (i), negative = _i < 0 ? 1 : 0;\
    const char digits[] = "0123456789";\
    char *str = malloc((size_t)log10(_i) + 2 + negative) + (int)log10(_i) + 1 + negative;\
    *str-- = 0;\
    for(; _i; _i /= 10) *str-- = digits[_i % 10];\
    if(negative) *str-- = '-';\
    ++str;\
  } while (0)

int main(){
 int i = 42;
 char *s = INTEGERTOSTRING(i);
 puts(s);
 return 0;
}
$ gcc test_43.c -o test_43 -lm
test_43.c: In function `main':
test_43.c:16: error: syntax error before "do"
test_43.c:16: error: `_i' undeclared (first use in this function)
test_43.c:16: error: (Each undeclared identifier is reported only once
test_43.c:16: error: for each function it appears in.)
test_43.c: At top level:
test_43.c:16: error: syntax error before "while"

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List