我想從一個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;
}
雙指針是嘗試使用c樣式的數組。它使得數組[x] [y]語法可以工作,但只有在你爲指向的指針實際分配內存的時候。我建議你忘記c樣式數組(它們很難安全使用)並閱讀關於std :: vector和/或std :: array的所有信息。你會更快樂。\ –