跳过行,然后从CSV文件读取十六进制值到2D数组

c++ Skip lines and then read hex values from a CSV file into a 2D arrary

本文关键字:十六进制 读取 数组 2D 文件 CSV 然后      更新时间:2023-10-16

我正在尝试使用c++从CSV文件读取十六进制值为2D数组。我是新手,所以我需要一些帮助。

我想跳过前98行(主要由文本组成),然后从文件中读取接下来的100行。有22个逗号分隔的列,我只需要8、10和13-20列。第8列包含一个字符串,其余部分包含十六进制值。

下面是我的。它编译(不知何故),但我一直得到分割错误。我想我需要动态地为数组分配空间。此外,代码没有考虑字符串或整型到十六进制的转换。

main当前没有做任何事情,这只是来自一个测试套件。

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <stdlib.h>
const int ROWS = 100; // CAN messages
const int COLS = 22; // Colums per message
const int BUFFSIZE = 80;
using namespace std;
int **readCSV() {
    int **array = 0;
    std::ifstream file( "power_steering.csv" );
    std::string line; 
    int col = 0;
    int row = 0;
    if (!file.is_open())
    {
        return 0;
    }
    for (int i = 1; i < 98; i++){
        std::getline(file, line); // skip the first 98 lines
    }
    while( std::getline( file, line ) ) {
        std::istringstream iss( line );
        std::string result;
        while( std::getline( iss, result, ',' ) ) {
            array[row][col] = atoi( result.c_str() );
            col = col+1;
        }
        row = row+1;
        col = 0;
    }
    return array;
}
int main() {
    int **array;
    array = readCSV();
    for (int i = 0; i < 100; i++) {
        cout<<array[i][0];
    }
    return 0;
}

您正在获得分段错误,因为您试图在array[row][col]中存储值而不为array分配内存。

我的建议:不要使用int** array;。使用std::vector<std::vector<int>> array;代替。这就避免了为代码中的对象分配和释放内存的需要。让std::vector为您处理内存管理

std::vector<std::vector<int>> readCSV() {
   std::vector<std::vector<int>> array;
   std::ifstream file( "power_steering.csv" );
   std::string line; 
   if (!file.is_open())
   {
      return array;
   }
   for (int i = 1; i < 98; i++){
      std::getline(file, line); // skip the first 98 lines
   }
   while( std::getline( file, line ) ) {
      std::istringstream iss( line );
      std::string result;
      std::vector<int> a2;
      while( std::getline( iss, result, ',' ) ) {
         a2.push_back(atoi( result.c_str() ));
      }
      array.push_back(a2);
   }
   return array;
}
int main() {
   std::vector<std::vector<int>> array = readCSV();
   for (int i = 0; i < 100; i++) {
      cout<<array[i][0];
   }
   return 0;
}