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

问题描述 投票:0回答:1

将字符串转换为双精度存在问题。我尝试过使用strtod,但这也是一样的。看起来这应该只是找到,但也许使用strtok与它有关。 data[i].calories当然是双重的。

data[i].calories = atof(strtok(NULL, ","));

它似乎给卡路里分配了一个正数或负数的大数(一个双数,这意味着它必须读错值。

预期数据:

12cx7,23:55:00, - > 0.968900025,(也可能是双倍),0,74,0,2,

实际得到的是:

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

编辑:

即时通讯I I IDIOT我将其作为INT PFFFFFFFFFFFFFFFF显示。

c string double atof
1个回答
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函数返回的任何错误。

© www.soinside.com 2019 - 2024. All rights reserved.