gpt4 book ai didi

c++ - 当这个值有逗号而不是点时,我如何读取浮点值?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:55:32 25 4
gpt4 key购买 nike

我有一个 CSV 文件,其中的值用逗号分隔,如下所示:

224,321,345,56.6
225,322,245,46.7
etc,etc,etc.....

所有值都必须被视为 float 。

问题是当我尝试将值读取为 float 时:

fscanf(file,%f,&value);

如果我打印结果

printf("The first value is: %f",value) 

我得到:

The first value is 224,321

当这个值有逗号而不是点时,如何读取浮点值?

最佳答案

C 解决方案

OP 的 scanf() 显然使用 "," 的浮点 decimal_point。不幸的是,数据使用 "."decimal_point

C 解决方案有 4 个步骤:1) 确定当前语言环境 2) 更改语言环境 3) 调用 sscanf() 4) 恢复语言环境。

#include <locale.h>

// Maybe CurrentLocaleName = "" will work.
// That's the locale-specific native environment.
// Otherwise the value may be available in preceding code.
const char *CurrentLocaleName = TBD();

// In the "C" locale, a decimal_point is ".".
if (NULL == setlocale(LC_NUMERIC, "C")) {
handle_local_change_error();
}

if (first_in_line) {
if (1 != fscanf(file, "%f", &value)) {
handle_scan_error();
}
}
else {
if (1 != fscanf(file, " ,%f", &value)) {
handle_scan_error();
}
}

if (NULL == setlocale(LC_NUMERIC, CurrentLocaleName)) {
handle_local_change_error();
}

关于c++ - 当这个值有逗号而不是点时,我如何读取浮点值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20007872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com