从文件中读取会忽略浮点中的小数



所以我在以下方面遇到了问题:

我将一个变量保存在配置文件中(它会精确地保存整个浮点数(,当我从配置文件中读取变量时,它会忽略浮点小数后的所有内容。

示例5.1234得出5.0000。我一定是犯了一个愚蠢的错误,我自己都无法发现,所以也许有更多知识的人可以发现。谢谢!

我有一个Options的结构,其中有一些默认值:

struct Options
{
float b_aX = 4.50f;
...
...
float* aX = &b_aX;
}

然后我试着从我为这个变量存储了一个新值的文件中读取:

ifstream file("c:\bllaa.cfg");
string str;  
float cfg[100] = {};
int total_lines = 0;
while (getline(file, str)) {
cfg[total_lines] = std::stoi(str);
total_lines++;
}  

//Finally read the value from the file and it comes out ignoring the decimals!
Options.aX[0] = cfg[0];

在文件ax=5.1234中从文件ax=5.0000 读取后

问题原因:
此行:

cfg[total_lines] = std::stoi(str);

由于使用了stoi,导致浮点值转换为整数。

解决方案:
使用stof将保持浮点值:

//----------------------vvvv------
cfg[total_lines] = std::stof(str);

最新更新