Converting numbers to Strings

This tip submitted by Webmaster on 2005-01-02 11:20:35. It has been viewed 91387 times.
Rating of 5.6 with 482 votes

Instead of writing your own function convert an integer or float to a string, just use the C function snprintf (in header stdio.h) or the C++ class stringstream (in header sstream).

In C:
#include <math.h>
#include <stdio.h>

char* itoa(int num)
    /* log10(num) gives the number of digits; + 1 for the null terminator */
    int size = log10(num) + 1;
    char *x = malloc(size);
    snprintf(x, size, "%d", num);

In C++:
#include <iostream>
#include <sstream>
#include <string>

string itoa(int num)
    stringstream converter;
    converter << num;
    return converter.str();

More tips

Help your fellow programmers! Add a tip!