2016-08-23 69 views
-4

我想从一个CSV文件使用C++读取十六进制值到二维数组。我比较新,所以我可以使用一些帮助。C++跳过行,然后从一个CSV文件读取十六进制值到一个2D文件

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

以下是我所拥有的。它编译(不知何故),但我不断收到分段错误。我想我需要为阵列动态分配空间。此外,该代码不考虑字符串或整数到十六进制转换。

主要目前没有做任何事情,这只是一个测试套件。

#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; 
} 
+1

双指针是尝试使用c样式的数组。它使得数组[x] [y]语法可以工作,但只有在你为指向的指针实际分配内存的时候。我建议你忘记c样式数组(它们很难安全使用)并阅读关于std :: vector和/或std :: array的所有信息。你会更快乐。\ –

回答

2

你得到分段错误,因为你想存储值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; 
} 
+0

这工作,谢谢!但是一些列包含以纯文本形式存储的1字节十六进制值(即FF或A7)。如果我将它们作为整数读入,则向量中将丢弃任何字母值。你知道解决这个问题的方法吗? – Kal

+0

@Kal,您需要使用不同的技术将字符串转换为“int”。见[这篇文章](http://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer)。 –

+0

通过用strtoul(result.c_str(),NULL,16) – Kal

相关问题