如何从字符串转换为双精度*
How to convert from a string to a double to a double*
我正在学习C++所以这可能是一个基本问题,但是,这是一个现实生活中的问题。我需要以最优雅/现代的方式从字符串转换为双精度*,然后以最优雅/现代的方式转换为双精度*(>C++98(。
该结构由基于 C 的框架提供(我在这里简化了代码,因为这只是问题的症结(,我无法更改框架,因为它与闭源 Metatrader4 交易应用程序(非基于 C(接口。编程接口需要将指针传递给结构。
字符串是从包含我从 Metatrader4 应用程序中获取的转储的 csv 文件中读取的。其细节超出了这个问题。但是,输入仍然是字符串,因此是源类型。
我很欣赏框架中使用的方法可能是旧的skool,但这是生活的一部分。这并不意味着我不能渴望在我的代码中做得更好,因此我要求优雅/现代的解决方案。如果它们不存在,那么我将被迫按照某人已经建议的那样使用 new。
我目前有以下无工作代码:
#include <string>
struct bidAsk
{
double *bid;
double *ask;
};
int main()
{
bidAsk ba;
ba.bid = std::stod("1.100");
ba.ask = &std::stod("1.102");
}
但是,上述两种转换方法都失败并出现转换错误。
第一行导致错误,指出:
E0513 a value of type "double" cannot be assigned to an entity of type "double *"
第二行导致以下错误:
E0158 expression must be an lvalue or a function designator
我也尝试过static_cast、const_cast、make_unique和(双*(选角,但没有运气。
提前谢谢。
问题是你需要一些实际值来指向你的指针。它们不能只指向从数字转换函数返回的临时值。
struct bidAsk
{
double* bid;
double* ask;
};
int main()
{
bidAsk ba;
// these have to exist somewhere that lives as long as the
// bidAsk object that points to them.
double bid_value = std::stod("1.100");
double ask_value = std::stod("1.102");
ba.bid = &bid_value; // just pointing to the real values above
ba.ask = &ask_value;
}
正如评论中提到的其他人,必须有人拥有指针指向的对象。
extern C {
struct bidAsk
{
double *bid;
double *ask;
};
}
struct BidAskWrapper
{
BidAskWrapper(const std::string& sbid, const std::string& sask)
:bid{std::stod(sbid)}, ask{std::stor(sask)}
{}
//Note: bidAsk valid only till the lifetype of the wrapper
bidAsk make_c_struct() {
return {&bid, &ask};
}
double bid, ask;
};
相关文章:
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 在 c++ 中从双精度转换为字符串
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- C++,遇到将双精度转换为整数的问题
- 在C++中将双精度转换为intptr_t
- 将大双精度转换为科学记数法以用作字符串?
- 了解双精度转换与整数转换中的整数与截断关系
- 将 OLE 自动化日期 (OADate) 双精度转换为结构 tm,而不使用 VariantTime到SystemTime
- 无法在赋值中将"双精度 (*)[4]"转换为"双精度**"
- 将大双精度转换为无符号 int 期间堆栈损坏
- 将双精度转换为本地8位
- 警告从"双精度"转换为"int"
- 如何将双精度转换为浮点指针
- 将双精度转换为整数时出错
- 使用并集将双精度转换为十六进制再转换为双精度
- 是否有可以将每个双精度转换为唯一uint64_t,保持精度和顺序的功能?(为什么我找不到?
- 使用定点表示法将双精度转换为字符串,没有尾随零和机智的冲刺
- 在C++中将双精度转换为字符*/字符串
- 无法将双精度 [] [] 转换为双精度 **