c++ - 使用二维数组读取 csv 文件
问题描述
我正在尝试使用二维数组读取 CSV 文件,但读取存在问题。文件的第一个单元格被跳过,然后继续读取所有内容。我不明白为什么它不读取第一个单元格。
#include<iostream>
#include<fstream>
#include<cstring>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string arrival,job[3][4];
ifstream jobfile("myfile.csv");
std::string fileCommand;
if(jobfile.is_open())
{
cout << "Successfully open file"<<endl;
while(getline(jobfile,arrival,','))
{
for(int i=1;i < 4;i++) //i = no. of job
{
for(int j=0; j<4; j++) // j = no. of processes
{
getline(jobfile,job[i][j],',');
cout << "Job[" << i << "]P[" << j << "]: "<< job[i][j]<< endl;
}
}//end for
}//end while
}//end if for jobfile open
jobfile.close();
}
解决方案
改变这个:
for(int i=1;i < 3;i++)
对此:
for(int i=0;i < 3;i++)
另外,删除 this getline(jobfile,job[i][j],',');
,因为您以这种方式跳过一行。当您在 while 循环的条件下调用 getline 时,它已经读取了一行(因此,现在,您必须存储该行。然后,当再次评估 while 循环的条件时,将读取下一行)。
但是,它变得比这复杂得多,因为您arrival
一次将持有一个令牌,直到它遇到当前行的最后一个令牌。在这种情况下,arrival
将是这样的:"currentLineLastToken\nnextLineFirstToken"
。
因此,您需要特别处理到达包含换行符的情况,string::find
用于此。
当找到换行符时,您应该将该字符串拆分为该换行符,以便提取所涉及的两个标记。用于string::substr
此。
此外,您不应该在 while 循环中循环使用 double for 来存储令牌,您只需阅读即可。job
只有在退出读取文件的 while 循环后,才可以使用双 for 循环进行打印。
把所有东西放在一起,我们得到这个:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string arrival,job[3][4];
ifstream jobfile("myfile.csv");
std::string fileCommand;
if(jobfile.is_open())
{
cout << "Successfully open file"<<endl;
int i = 0, j = 0;
while(getline(jobfile,arrival,','))
{
//cout << "|" << arrival << "|" << endl;
size_t found = arrival.find("\n");
if (found != std::string::npos) // if newline was found
{
string lastToken = arrival.substr(0, found);
string nextLineFirstTOken = arrival.substr(found + 1);
job[i++][j] = lastToken;
j = 0;
if(nextLineFirstTOken != "\n") // when you read the last token of the last line
job[i][j++] = nextLineFirstTOken;
}
else
{
job[i][j++] = arrival;
}
}//end while
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 4; ++j)
{
cout << job[i][j] << " ";
}
cout << endl;
}
}//end if for jobfile open
jobfile.close();
}
输出(用于我的自定义输入):
Successfully open file
aa bb cc dd
bla blu blo ble
qq ww ee rr
推荐阅读
- swagger - 如何在 openapi 3 中描述分段上传中的名称
- c# - 使用 C# 将 XPS 字形渲染到位图
- regex - xsd 文件中的 html(s) 正则表达式验证
- ubuntu - 无法在ubuntu中下载腻子
- angular - 从 Angular 中的数组数据创建表
- sql - ORA-01810: 格式代码在 SQL 中出现两次
- arm - Cortex-A8 乱序执行和 Spectre
- python - 为什么 numpy 会保留这么多未使用的内存?
- macos - 全新安装monogame,如何解决警告
- performance - 如何在没有循环且时间复杂度较低的情况下从数组列表中删除一些项目?