簡體   English   中英

如何從.csv文件中讀取值並將其存儲在向量中?

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

我使用Windows 7上的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

奇怪的是,它在Windows 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第1行中的每個值執行myValues.push_back(x)
  3. 使用csv第二行中的每個值執行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, ';')) {..}

每個循環將文本放入std::string

然后,您將需要轉換為數字數據類型並推入向量,但這將使您入門。

另外,為什么對列和行數使用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()刪除它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM