I am trying to read hex values into a 2D array from a CSV file using c++. I am relatively new, so I could use some help.
I want to skip the first 98 lines (which consist mostly of text) and then read in the next 100 lines from the file. There are 22 comma separated columns and I only really need columns 8, 10, and 13-20. Column 8 contains a string and the rest contain hex values.
Below is what I have. It compiles (somehow) but I keep getting a segmentation fault. I think I need to dynamically allocate space for the array. Also, the code doesn't account for the string or int to hex conversion.
The main isn't doing anything currently, this is just from a test suite.
#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;
}