在C++中将双精度转换为字符*/字符串

Convert doubles to char*/string in C++

本文关键字:字符 字符串 转换 C++ 双精度      更新时间:2023-10-16

我很确定这不是一项艰巨的任务,但我不明白是什么导致了问题,我想真正理解这一点,因为我经常遇到一些与指针/数组/强制转换相关的问题:

我将边界框值存储在双精度*

// this is the calss-variable
double *_boundingBox;
// this is where I put some data in it
double boundingBox[6];
boundingBox[0] = 
.
.
.
boundingBox[6] = ....; 
// set pointer to boundingbox
_boundingBox = &boundingBox;

在另一个类中,我使用它

double* getBoundingBoxInfo()
{
    return _boundingBox;
}

获取我的边界框数据,我想将其输入到 QLabel 中作为 QString

double boundingBox[6];
boundingBox[0] = *_drawer->getBoundingBoxInfo();
std::string stringX = "x start: " <<  boundingBox[0] << "tx end: " <<   boundingBox[3];
QLabel *labelX = new QLabel(QString(stringX.c_str()));

当前的编译错误是

错误:"常量字符 [10]"和"double"类型的操作数无效为二进制"运算符<<

有人可以告诉我这应该如何工作吗?我是否按照它们应该使用的方式使用双*、双倍 [] 和字符串?

不能按

原样将数据流式传输到std::string中。解决方案是使用std::ostringstream

std::ostringstream out;
out << "x start: " <<  boundingBox[0] << "tx end: " <<   boundingBox[3];
std::string stringX = out.str();

您得到的编译错误是针对"x start: " << boundingBox[0]

"x start: "的类型是const char*boundingBox[0]的类型是double

但是operator<<(const char*,double)没有定义.

您可以使用 ostringstream 对象使其工作:

ostringstream oss;
oss << "x start: " << boundingBox[0] << "tx end: " << boundingBox[3];
std::string stringX = oss.str();

作为旁注,当你设置_boundingBox = &boundingBox时,你不需要&,因为boundingBox是一个数组,所以本质上是boundingBox == &boundingBox

这样做的原因(如果您想知道)是数组没有 l 值,并且您无法更改数组的值(例如,您无法执行boundingBox = ... )。

QString提供了一切 http://qt-project.org/doc/qt-4.8/qstring.html#arg-20

所以只需使用

QString("some text for double value: %1").arg(yourdouble, <additional parameters>)

在您的情况下:

... new QLabel(QString("x start: %1tx end: %2").arg(boundingBox[0]).arg(boundingBox[3]));