如何从字符串转换为双精度*

How to convert from a string to a double to a double*

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

我正在学习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;
};