Convert integer to string (char *)
/*
* IntToStr.cpp
*
* Created on: Apr 12, 2012
* Author: Kiran Hegde
*/
#include <iostream>
using namespace std;
void intToString(int n, char *str) {
bool isNeg = false;
if (n < 0) {
isNeg = true;
n = -n;
}
int index = 0;
do {
str[index++] = (n % 10) + '0';
n = n / 10;
} while (n > 0);
if (isNeg) {
str[index++] = '-';
}
str[index] = '\0';
//now reverse
int start = 0;
int end = index - 1;
char temp;
while (start < end) {
temp = str[start];
str[start++] = str[end];
str[end--] = temp;
}
}
/**
* Test the function
*/
int main() {
char str[16];
int test = -234567;
cout << "Integer: " << test << endl;
intToString(test, str);
cout << "String: " << str << endl;
}