I saw a post on here asking how to convert a double variable value into a char array. Someone said to just use stringstream but didn't explain why it works. I tried googling but couldn't find any documentation on specifically how it converts it. I was wondering if someone could explain to me how it works. Here is the code I wrote that converts a double variable value into a char array.
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double a = 12.99;
char b[100];
stringstream ss;
ss << a;
ss >> b;
cout << b; // it outputs 12.99
return 0;
}
When you do ss << a;
you are inserting the double in the stringstream
(let's suppose it holds the value in a string
) and so when you run ss >> b;
it just copies the string
in the char[]
char by char.
Now the only point is to convert double
to string
, thing that can be achieved with a simple algorithm:
std::string converter(double value){
char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
bool is_negative = value < 0;
std::string integer_to_string;
value = is_negative ? value * -1 : value; // make the number positive
double fract = value - static_cast<unsigned int>(value); // fractionary part of the number
unsigned int integer = static_cast<int>(value); // integer part of the number
do{
unsigned int current = integer % 10; // current digit
integer_to_string = std::string(1, digits[current]) + integer_to_string; // append the current digit at the beginning
integer = integer / 10; // delete the current digit
} while(integer > 0); // do over and over again until there are digits
integer_to_string = (is_negative ? "-" : "") + integer_to_string; // put the - in case of negative
std::string fract_to_string;
if(fract > 0) {
fract_to_string = ".";
do {
unsigned int current = static_cast<int>(fract * 10); // current digit
fract_to_string = fract_to_string + std::string(1, digits[current]); // append the current digit at the beginning
fract = (fract * 10) - current; // delete the current digit
} while (fract > 0);
}
return integer_to_string + fract_to_string;
}
Keep in mind that this is a very basic conversion and will have a lot of errors due to the instability of the operator-
in floating point operation, and so it's a lot unstable, but it's just an example
NOTE: this absolutely to avoid to use in legacy (and actually not only legacy) code, it's just been done as an example, instead you should use std::to_string()
with will perform it faster and without any type of error (check this )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.