I'm trying to convert a double w/ a string of characters w/o using sprintf and padding w/ 0's.. omg... driving me nutz..
what I have thus far..
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <deque>
using namespace std;
void d2s(double,char[], unsigned int);
int main()
{
while (true)
{
double num;
unsigned int size;
printf ("Input number: ");
cin >> num;
printf ("Input size of char array: ");
cin >> size;
char* s = new char[size];
dtoa(num, s, size);
printf("printf %s\n",s);
cout << " cout = " << s << endl;
}
}
void d2s(double num, char s[], unsigned int width)
{
--width; // allow room for \0.
double decimal = abs(num) - abs(int(num));
int integer = abs(int(num));
deque<char> result;
while (integer != 0)
{
result.push_front(integer % 10 + '0');
integer /= 10;
}
if (num < 0) // check for negative value
result.push_front('-');
if (decimal != 0) // check for decimal value
result.push_back('.');
while (abs(decimal) != 0 && result.size() < width)
{
decimal *= 10;
result.push_back(int(decimal) % 10 + '0');
decimal = decimal - int(decimal);
}
while (result.size() < width)
{
result.push_front(' '); // pad with spaces.
}
for (int i=0; i<width; ++i) // results into array s
{
s[i] = result[i];
}
s[width] = '\0';
}