我在这里看到一个帖子,问如何将一个双变量值转换为一个char数组。有人说用stringstream就可以了,但没有解释为什么会这样。我试着上网查了一下,但找不到任何文档具体说明它是如何转换的。我想知道是否有人能给我解释一下它的工作原理。这是我写的代码,它将一个双变量值转换为一个char数组。
#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;
}
当你做 ss << a;
你是在 stringstream
(假设它的数值在 string
),所以当你运行 ss >> b;
它只是复制 string
在 char[]
char by char。现在唯一的重点是将 double
到 string
的事情,可以用一个简单的算法来实现。
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;
}
请记住,这是一个非常基本的转换 并将有很多错误 由于不稳定的。operator-
在浮点运算中,所以它有很多不稳定的地方,但这只是一个例子。
注意:这绝对是为了避免在旧版(实际上不仅仅是旧版)代码中使用,它只是作为一个例子,而你应该使用 std::to_string()
将更快地执行它,而不会出现任何类型的错误(检查 这个)