簡體   English   中英

使用Vector函數C ++從文件中讀取特定數據

[英]Reading the specific data from the file using Vector function C++

我是C ++的新手,從文件導入特定數據(數字)有困難。 我的輸入如下所示:

Open    High    Low     Close
1.11476 1.11709 1.10426 1.10533
1.10532 1.11212 1.10321 1.10836
1.10834 1.11177 1.10649 1.11139
1.09946 1.10955 1.09691 1.10556  
1.10757 1.11254 1.09914 1.10361
1.10359 1.12162 1.10301 1.11595
1.09995 1.10851 1.09652 1.10097

我使用下面的代碼對我來說很合適,它可以完全讀取第二列,但是我只需要讀取特定的數據。 例如,第三行/第三列是1.10649

如何讀取特定數據? 我是否需要使用字符串來獲取行/列,然后將其轉換為int以便在向量中讀取它? 我願意提出任何建議,如果有任何幫助可以解決此問題,我將不勝感激。

// Data import 2nd Column

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>

using namespace std;

int main()
{
const int columns = 4;

    vector< vector <double> > data;

  ifstream market_data("market_data.txt");

    if (market_data.is_open()) {
        double num;

        vector <double> line;

        while (market_data >> num) {
            line.push_back(num);

            if (line.size() == columns) {
                data.push_back(line);
                line.clear();
            }
        }
    }

    vector <double> column;
    double col = 2;

    for (double i = 0; i < data.size(); ++i) {
        column.push_back(data[i][col - 1]);
        cout << column[i] << endl;
    }

    system ("pause");
    return 0;
}

您需要使用整數值進行索引(准確地說是size_t ),

 for (double i = 0; i < data.size(); ++i) {

 for( size_t i = 0; i < data.size(); ++i) {
   // ^^^^^^

否則,從您的代碼示例來看,一切似乎都很好。

如果您的數字將始終包含7個字符(我假設它不是二進制文件),則可以簡化此過程。

使用ifstream的seekg()方法。

每個數字填充10個字符(7個數字,3個空格)。 因此,如果您有表格ROWS x COLUMNS,那么要獲取特定編號,可以執行以下操作:

const int ROW_LEN = 4
const int DATA_LEN = 10
...
int row,column;
double num;

std::cin >> row; //assume first row is 0
std::cin >> column //assume first column is 0

marked_data.seekg((column*ROW_LEN + row)*DATA_LEN);

marked_data >> num // here is your number

謝謝您的答復。我已經解決了這個問題。 所以代替:

vector <double> column;
    double col = 2;

for (double i = 0; i < data.size(); ++i) {
    column.push_back(data[i][col - 1]);
    cout << column[i] << endl;
}


足以寫:

cout << data [2] [2] << endl;

暫無
暫無

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

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