将字符串从.csv文件转换为双精度

时间:2019-01-24 05:46:43

标签: c string double atof

在将字符串转换为双精度时遇到麻烦。我尝试使用https://ident.me/.json ,但是这样做也是一样的。似乎应该可以找到它,但是使用strtod可能与此有关。 strtok是当然的一倍。

data[i].calories

似乎给卡路里分配了一个正数或负数(真的是两倍),这意味着它必须错误地读取了数值。

预期数据:

  

12cx7,23:55:00,-> 0.968900025,(也可以是双精度),0,74,0,2,

实际上得到的是:

  

12cx7,23:55:00,->-537691972,0,0,74,0,2,

编辑:

我是笨蛋,我将其显示为整数PFFFFFFFFFFFFFFFFFF。

1 个答案:

答案 0 :(得分:0)

假设我们有这样的输入

  

12cx7,23:55:00,0.968900025,,0,74,0,2,

我们希望

  

“在将字符串转换为双精度时遇到麻烦。”

这就是我们想要分隔字母数字数据的原因。然后剩下的整数和浮点数,我们要以正确的格式打印,我将执行以下操作:

#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int isNumeric (const char * s)
{
    if (s == NULL || *s == '\0' || isspace(*s)) {
      return 0;
    }
    char * p;
    strtod (s, &p);
    return *p == '\0';
}

bool isInteger(double val)
{
    int truncated = (int)val;
    return (val == truncated);
}

int main() {
    // If this is your input:
    char input[100] = "12cx7,23:55:00,0.968900025,0,74,0,2,";
    // Then step 1 -> we split the values
    char *token = std::strtok(input, ",");
    while (token != NULL) {
        // Step 2 -> we check if the values in the string are numeric or otherwise
        if (isNumeric(token)) {
            // printf("%s\n", token);
            char* endptr;
            double v = strtod(token, &endptr);
            // Step 3 -> we convert the strings containing no fractional parts to ints
            if (isInteger(v)) {
                int i = strtol(token, &endptr, 10);
                printf("%d\n", i);
            } else {
                // Step 4 -> we print the remaining numeric-strings as floats
                printf("%f\n", v);
            }
        }
        else {
            // What is not numeric, print as it is, like a string
            printf("%s,",token);
        }
        token = std::strtok(NULL, ",");
    }
}

对于isInteger()函数,我从this接受的答案中获取了想法/代码。其余的都是原始的,可能可以改进/改进。

这将产生以下输出:

  

12cx7,23:55:00,0.968900,0,74,0,2,

基本上是我们想要的输出,除了非常重要的区别是输入是一个完整的单个字符串,输出是正确识别并以正确格式打印的双精度/浮点型,整数和字符串。

编辑

在这里我没有做任何错误处理。这段代码只是为了给OP提供概念验证。检查并控制使用的strtoX函数返回的任何错误。

相关问题