[英]Read csv file using 2d array
我正在嘗試使用二維數組讀取 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 循環內循環使用 double for 來存儲令牌,您只需閱讀即可。 只有在退出讀取文件的 while 循環后,才使用雙 for 循環,當需要打印job
時。
把所有東西放在一起,我們得到這個:
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.