如何将csv文本文件读取到二维数组中

How do i read a csv text file into a 2D array?

本文关键字:读取 二维数组 文件 文本 csv      更新时间:2024-04-27

这是示例文本文件内容:

5//列

Id、年龄、历史、化学、生物学//列名

100//数据行数

3245167,12,45,78,12//用逗号分隔的数据行

30980424,10,26,38,98

等等。

这是我目前为止的通用代码:

int main()
{
//prints out input from file.
ifstream myFile;
myFile.open("WRITE FILE NAME");
while(Myfile.good()) { // good means while there is smthg in the file keep reading it
// until you reach to the end.
string line;
getline(myFile, line, ','); //read text until comma, then stop and store in variable.
cout << line << endl;
}
return 0;
}

您对解析文件本身有了大致的了解,数据将从左到右从文件中读取。因此,在这一点上,我建议您做两件事,因为您已经解析了数据。你可能想要一些东西来保存它,比如一个队列来存储和保存所有数据,还有一个double-for循环来将它放入2D阵列中,就像这样:

std::queue<string> holder;
std::string myArray[row][col];
getline(myFile, line, ',');
holder.push(line);
for(int i=0; i < row; i++)
{ 
for(int j=0; j < col; j++)
{
myArray[i][j] = holder.pop();
}
}