在C++中将双精度转换为字符*/字符串
Convert doubles to char*/string in C++
我很确定这不是一项艰巨的任务,但我不明白是什么导致了问题,我想真正理解这一点,因为我经常遇到一些与指针/数组/强制转换相关的问题:
我将边界框值存储在双精度*
// 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]));
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数