跳过行,然后从CSV文件读取十六进制值到2D数组
c++ Skip lines and then read hex values from a CSV file into a 2D arrary
我正在尝试使用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;
}
相关文章:
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- 在 c++ 中从文本文件中读取两个十六进制值
- 正在读取十六进制文件C++
- 写入和读取十六进制 TRAM QT 串行端口
- 从串行端口(POSIX)读取十六进制值
- 如何在C 中的Little Endian中读取来自二进制文件的单独的十六进制字符
- C++如何从文件中读取十六进制字节并将其存储为指针
- char* 如何读取十六进制的这个整数?它在 ostream::write() 中是如何工作的
- C++/CPP 读取添加的十六进制地址
- 为什么将uint8_t读取为十六进制没有按预期工作?
- 在十六进制中读取的数字在C 中给出了错误的数字
- 如何从字符中读取ASCII值并将其转换为十六进制格式的字符串
- 从 bin 文件 -c++ 中读取十六进制数字为每个字符 2 位数字
- 在十六进制编辑器中写入程序内存,并以编程方式读取
- 从 C++ 中的 txt 文件中读取十六进制
- 从文件中读取 4 个十六进制值并转换为浮点数
- 从ini文件中读取十六进制字符
- 从二进制文件读取/写入十六进制字节
- 在C++中以十六进制读取文件
- 以十六进制读取/写入二进制对象