c++如何从.csv文件中读取值并将其存储在矢量中

c++ How can I read values from a .csv file and store them in a vector?

本文关键字:存储 读取 csv c++ 文件      更新时间:2023-10-16

我在Windows7上使用Code::Blocks从.cpp文件中制作小.exe,我是一个初学者(对不起!)

这是今天的问题:

我有一个.csv文件,其中包含用分号分隔的长整数(从0到2^16),并列为一系列水平行。

我将在这里举一个简单的例子,但事实上,文件的大小可能高达2Go。

假设我的文件wall.csv在文本编辑器(如Notepad++:)中显示为这样

350;3240;2292;33364;3206;266;290
362;314;244;2726;24342;2362;310
392;326;248;2546;2438;228;314
378;334;274;2842;308;3232;356

奇怪的是,它在窗口notepad 中显示为这样

350;3240;2292;33364;3206;266;290
362;314;244;2726;24342;2362;310
392;326;248;2546;2438;228;314
378;334;274;2842;308;3232;356

不管怎样,

假设我知道并将在3个float变量中声明文件中的列数、行数和值。

int col = 7;   // amount of columns
int lines = 4; // amount of lines
float x = 0;     // a variable that will contain a value from the file  

我想要:

  1. 创建vector <float> myValues
  2. 对csv第一行中的每个值执行myValues.push_back(x)
  3. 对csv第2行的每个值执行myValues.push_back(x)
  4. 第三行中的每个值执行myValues.push_back(x)。。。等等

,直到文件完全存储在向量myValues中

我的问题:

我不知道如何将csv文件中的值依次分配给变量x

我该怎么做?


好的,这个代码工作(相当慢,但还好!):

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int col = 1221;   // amount of columns
int lines = 914; // amount of lines
int x = 0;     // a variable that will contain a value from the file
vector <int> myValues;
int main() {
    ifstream ifs ("walls.tif.csv");
    char dummy;
    for (int i = 0; i < lines; ++i){
        for (int i = 0; i < col; ++i){
            ifs >> x;
            myValues.push_back(x);
            // So the dummy won't eat digits
            if (i < (col - 1))
                ifs >> dummy;
        }
    }
    float A = 0;
    float B = col*lines;
    for (size_t i = 0; i < myValues.size(); ++i){
        float C = 100*(A/B);
        A++;
        // display progress and successive x values
        cout << C << "% accomplished, pix = " << myValues[i] <<endl;
    }
}

将文本数据放入stringstream并使用std::getline

它需要一个可选的第三个参数,即"end-of-line"字符,但您可以使用;而不是真正的end of line

呼叫while (std::getline(ss, str, ';')) {..}

并且每个循环将文本放入CCD_ 16中。

然后,您需要转换为数字数据类型并推送为向量,但这将使您开始。

另外,为什么要使用floats来表示列数和行数?

它们是整数值。

尝试使用C++标准模板库的输入操作。

制作一个伪字符变量来吃掉分号,然后将cin数字放入x变量中,如下所示:

char dummy;
for (int i = 0; i < lines; ++i){
    for (int i = 0; i < col; ++i){
        cin >> x;
        myValues.push_back(x);
        // So the dummy won't eat digits
        if (i < (col - 1))
            cin >> dummy;
    }
}

要这样做,你可以重定向你的csv文件,从命令行输入,如下所示:

yourExecutable.exe < yourFile.csv

要循环通过充满数据的矢量:

for (size_t i = 0; i < myVector.size(); ++i){
    cout << myVector[i];
}

上面,size_t类型由STL库定义,用于抑制错误。

如果您只想使用一次值,并在使用时将其从容器中删除,那么最好使用std::queue容器。通过这种方式,您可以使用front()查看front元素,然后使用pop()将其移除。