如何按列解析 CSV 并保存到数组 C++

How to parse CSV by columns and save into arrays C++

我是 C++ 的新手。我在 Data.csv 中保存了一些数据,如下所示:

     S0001       S0002     S0003   S0004    ...
0   10.289461  17.012874         
1   11.491483  13.053712         
2   10.404887  12.190057          
3   10.502540  16.363996  ...        ...
4   11.102104  12.795502         
5   13.205706  13.707030         
6   10.544555  12.173467         
7   10.380928  12.578932        
...    ...         ...         ...     ...  

我需要逐列的值来进行计算(列平均值、移动平均值等),所以我想按列解析并将它们保存到数组中。

我阅读了 these 个答案,但没有找到我想要的。我做的是

void read_file(std::vector<std::string>& v, std::string filename){
    std::ifstream inFile(filename);
    std::string temp;
    if (!inFile.is_open()) {
        std::cout<<"Unable to open the file"<<std::endl;
        exit(1);
    }
    while (getline(inFile, temp)) {
        v.push_back(temp);
    }
    inFile.close();
}

int main()
{
    std::string filename = "Book1.csv";
    std::vector<std::string> vec;
    read_file(vec, filename);
    std::cout<<vec[1]<<std::endl;
 }

我只能逐行获取值。但是如何解析文件并按列获取值?

您只能逐行读取文本文件。如果您只需要一列(不太可能),您可以将该行中的值解析出来并将其推入一个向量中。

如果您需要一次性加载所有列,请创建 vectorvector 并将解析后的值推送到不同的列向量中。