在读取.csv时将数组类型字符串转换为double

converting array type string to double with .csv read

本文关键字:字符串 转换 double 类型 数组 读取 csv      更新时间:2023-10-16

我正在接受一个.csv文件,其中包含字符串并将一定范围内的所有内容转换为double类型。我的目标实际上只是捕获第四列,但如果我想捕获更多,将它们全部作为一个矩阵似乎是最好的方法。但是,当我将字符串类型转换为double类型时,这些转换对我来说没有意义。

表示"24 Month"的字符串将被转换为值24。但是,表示"4.35183217"的字符串将被转换为0(实际上它是一个非常小的负数)。为什么会这样?

见这里的输入查看这里的输出

double data[38][27];
std::ifstream file("YC Rate Levels.csv");
for (int row = 0; row < 38; ++row)
{
    std::string line;
    std::getline(file, line);
    if (!file.good())
        break;
    std::stringstream iss(line);
    for (int col = 0; col < 27; ++col)
    {
        std::string val;
        std::getline(iss, val, ',');
        if (!iss.good())
            break;
        std::stringstream convertor(val);
        convertor >> data[row][col];
    }
}
std::cout << "Col 3" << " - " << "Col 4" << std::endl;;
for (int i = 0; i < 38; ++i)
{
    std::cout << data[i][3] << " - " << data[i][4] << std::endl;
}
std::cin.clear(); // reset any error flags
std::cin.ignore(32767, 'n'); // ignore any characters in the input buffer until we find an enter character
std::cin.get(); // get one more char from the user
return 0;

您的数据未初始化且未定义,这就是为什么它默认为一些小数字。您可以初始化如下:double data[38][27]={0};或更好,但使用std::vector

其次,*.csv文件是这样的:
"abc", "123", "345"

有一个额外的空格或引号。字符串表示为""345"",不转换为345.00

使用std::stod而不是stringstream,当输入不能转换时将抛出异常。例子:

try 
{
    double temp = std::stod(val);
}
catch (...)
{
    std::cout << "bad input: " << val << std::endl;
}

使用下面的函数从文本的左/右删除引号和空格:

void trim(std::string& s, const char* t)
{
    s.erase(0, s.find_first_not_of(t));
    s.erase(s.find_last_not_of(t) + 1);
}

把它放在一起:

std::vector<std::vector<double>> data;
std::string line;
while(std::getline(file, line))
{
    std::vector<double> row;
    std::stringstream iss(line);
    std::string val;
    while (std::getline(iss, val, ','))
    {
        trim(val, " "");
        try 
        {
            double temp = std::stod(val);
            row.push_back(temp);
        }
        catch (...)
        {
            std::cout << "bad input: " << val << std::endl;
        }
    }
    std::cout << "n";
    data.push_back(row);
}
for (const auto &row : data)
{
    for (const auto &col : row)
        std::cout << col << ", ";
    std::cout << "n";
    //if (data[i].size() > 4) std::cout << data[i][4] << "n";
}