gpt4 book ai didi

c++ - 使用二维数组读取 csv 文件

转载 作者:行者123 更新时间:2023-11-30 04:54:25 52 4
gpt4 key购买 nike

我正在尝试使用二维数组读取 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++)

此外,删除此 getline(jobfile,job[i][j],',');,因为这样会跳过一行。当您在 while 循环的条件中调用 getline 时,它​​已经读取了一行(结果,现在,您必须存储该行。然后,当再次评估 while 循环的条件时,将读取下一行).


但是,它变得比这复杂得多,因为您 arrival 将一次持有一个标记,直到它遇到当前行的最后一个标记。在这种情况下,arrival 将是这样的:"currentLineLastToken\nnextLineFirstToken"

因此,您需要特别处理到达包含换行符的情况,使用string::find为此。

当找到换行符时,您应该将该字符串拆分为该换行符,以便提取涉及的两个标记。使用 string::substr为此。

此外,您不应该在 while 循环中循环使用双 for 来存储 token ,您只是阅读。使用双 for 循环,当需要打印 job 时,仅在退出读取文件的 while 循环之后。

将所有内容放在一起,我们得到:

#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

关于c++ - 使用二维数组读取 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53628338/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com