首页 > 解决方案 > 使用二维数组读取 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();    
}

标签: c++filecsv

解决方案


改变这个:

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

推荐阅读