将双精度值转换为 char 变量时字符串流如何工作
How does stringstream work when converting a double value into a char variable
>我在这里看到一篇文章,询问如何将双精度变量值转换为字符数组。有人说只使用字符串流,但没有解释它为什么有效。我尝试谷歌搜索,但找不到任何关于它如何转换它的文档。我想知道是否有人可以向我解释它是如何工作的。这是我编写的代码,它将双精度变量值转换为 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;
时,它只是逐个字符复制char[]
字符中的string
string
double
。 可以通过简单的算法实现的事情:
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()
with 将更快地执行它并且没有任何类型的错误(检查这个(
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?