【问题标题】:Reading a particular line in a csv file in C++ [duplicate]在 C++ 中读取 csv 文件中的特定行 [重复]
【发布时间】:2013-08-09 20:52:41
【问题描述】:

我有一个包含多行数据的 csv 文件。我的函数将 lineNum 作为参数传递。因此,当用户输入 4 作为 lineNum 时,我想读取 csv 文件中的第 4 行。 我认为解决此问题的一个好方法是查找 \n 并计算它们,当计数为 lineNum-1 时停止,然后继续阅读下一行。 我认为这是一种不错的方法,但我对实现完全感到困惑。希望得到一些帮助 这是我的代码

void ReadCsv( int lineNum){
    ifstream inFile ("/media/LOGGING/darsv1.csv");
    string line;
    string dataArray[226900];
    int i = 0;
    int endofline =0;
    int a, b, c, d, e;
    while (getline (inFile, line)) {
        //printf(line.c_str());
        istringstream linestream(line);
        string item ="";
        int itemnum = 0;
        if (lineNum==1) {
            printf(" line number is 1. ");
            while (getline (linestream, item, ',')) {
            itemnum++;
            dataArray[i]=item;
            i++;
            }
        }
        else {
            while (getline (linestream, item,'\n')) {
                endofline=endofline+1;
                cout<<"  went through line number  "<<endofline<<" ";
                printf(" inside inner while, looking for line. ");
                if (endofline == lineNum-1) {
                    printf(" found the correct line. ");
                    while (getline (linestream, item, ',')) {
                        itemnum++;
                        dataArray[i]=item;
                        i++;
                        printf(" found the correct data in the line. ");
                    }
                }
            }printf(" out of inner while. ");
        }printf(" out of outer if. ");
   }
   printf(" out of all while loops. ");
}

【问题讨论】:

    标签: c++ csv


    【解决方案1】:

    如果您只需要读取 CSV 中的某一行,然后从该行读取逗号分隔的项目,那么这可能会有所帮助。我同意@sanjaya-r 的观点,你应该保持简单。

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    using namespace std;
    
    int main (int argc, const char * argv[]) {
        string line, csvItem;
        ifstream myfile ("/tmp/file.csv");
        int lineNumber = 0;
        int lineNumberSought = 3;  // you may get it as argument
        if (myfile.is_open()) {
            while (getline(myfile,line)) {
                lineNumber++;
                if(lineNumber == lineNumberSought) {
                    cout << line << endl; ;
                    istringstream myline(line);
                    while(getline(myline, csvItem, ',')) {
                        cout << csvItem << endl;
                    }
                }
            }
            myfile.close();
        }
        return 0;
    }
    

    【讨论】:

    • 如果您正确使用 getline,则不必检查 myfile.eof() - 特别是在某些情况下这是一种不好的做法。您可以在not using ios::eof but istream::getline correctly 上阅读更多关于其他 SO Q&A 的内容!
    • 感谢 DanielTuzes,我更新了 sn-p。
    • 感谢 mk,这对我来说完全有用,而且很容易理解 :)
    【解决方案2】:

    目前无法编译。

    这是你的错误吗?

    if (endofline = lineNum-1)
    

    您正在分配 lineNum - 1 到 endofline。使用== 进行比较。

    【讨论】:

    • 这是我的一个错误,感谢您指出,但我仍然认为它读取的行号不正确,我认为有一个我无法修复的逻辑错误。
    • 显示你的一些输入输出日志,包括你认为有错误的部分。
    • 当我使用 csv 文件运行此函数时,lineNum = 5,输出显示为“在内部 while 中通过第 1 行,正在寻找行。out of inner while。out of external if . 通过第 2 行 ....继续... 在内部 while 中通过第 6 行,寻找行。在内部同时。如果在外部外部。通过第 7 行“所以它不会停在第 7 行5.
    【解决方案3】:

    保持简单。让一个 getline 循环完成所有工作。第一行不需要特殊情况。

    // ...
    linesToGo = linesNum - 1;
    string line;  
    while(getline(infile,line) && (linesToGo > 0)) {
        linesToGo--;
    }
    if (linesToGo == 0) {
        cout << "found line:," << line << endl;
        // process here.
    } else {
        count << "not enough lines in file." << endl;
    }
    

    另外,不要混合使用 cout 和 printf。

    【讨论】:

      【解决方案4】:

      way to go a specific line in a text file 上有一个 SO 问题和答案,您可以在其中找到我最喜欢的 Xeo 的答案。 Xeo 使用istream::ignore,足够的功能,所以它是干净和快速的解决方案。

      这是一个基于上述答案的完整示例(带有一些装饰):

      #include <fstream>
      #include <limits>
      #include <string>
      #include <iostream>
      
      using namespace std;
      
      
      
      fstream& Go2Line(fstream& file, unsigned int num)
      {
          file.seekg(ios::beg);
          for(unsigned int i=0; i < num - 1; ++i)
              file.ignore(numeric_limits<streamsize>::max(),'\n');
      
          return file;
      }
      
      
      
      int main()
      {
          fstream file("/media/LOGGING/darsv1.csv",ios_base::in);
          if (!file)
              cout << "Unable to open file /media/LOGGING/darsv1.csv\n";
          else 
          {
              int Number2Go = 4;
              Go2Line(file, Number2Go);
      
              if (!file)
                  cout << "Unable to reach line " << Number2Go << ".\n";
              else
              {
                  string line;
                  getline(file,line);
                  cout << "Line " << Number2Go << "reached successfully. It is:\n" << line;
              }
          }
      
          return 0;
      }
      

      【讨论】:

        【解决方案5】:

        我创建了以下程序,因为我正在练习 C++ 算法。虽然该解决方案似乎有效,但请持保留态度(即,有些人可能认为它太复杂了)。另一方面,它可以帮助您了解迭代器、流和算法的某些方面。

        #include<iostream>
        #include<fstream>
        #include<algorithm>
        #include<iterator>
        
        /**
           @brief A trick proposed by Jerry Coffin / Manuel (SO users) to
                 create a line-by-line iterator. This makes an `std::istream`
                 yield lines as opposed to chars.
         */
        struct Line
            : std::string { 
          friend std::istream & operator>>(std::istream& is, Line& line) {   
            return std::getline(is, line);
          }
        };
        
        /**
           @brief This predicate contains an internal count of the lines read
           so far. Its `operator()(std::string)` will evaluate to `true` when
           the current line read equals the target line (provided during
           construction).
        
         */
        struct LineNumberMatcher {
          unsigned int target_line;
          unsigned int current_line;
        
          LineNumberMatcher(unsigned int target_line)
              : target_line(target_line),
                current_line(0) { }
        
          bool operator()(const std::string& line) {
            return ++current_line == target_line;
          }
        };
        
        int main(int argc, char* argv[]) {
          if(argc != 3) {
            std::cout<<"usage: "<<argv[0]<<" filename line"<<std::endl;
            return 0;
          }
        
          std::string filename(argv[1]);
          unsigned int target = std::stoi(argv[2]);
        
          // Build the LineNumberMatcher
          LineNumberMatcher match(target);
        
          // Provide a scope after which the file will be automatically closed
          {
            // Open the file
            std::ifstream fp(filename);
        
            // Copy the line to standard output if the LineNumberMatcher
            // evaluates to true (that is, when the line read equals the target
            // line)
            std::copy_if(std::istream_iterator<Line>(fp),
                         std::istream_iterator<Line>(),
                         std::ostream_iterator<std::string>(std::cout, "\n"),
                         match);
          }
        
          return 0;  
        }
        

        使用 C++11 支持编译(在我的例子中,g++ spitline.cpp -std=c++111,使用 GCC 4.7.2)。示例输出:

        $ /a.out spitline.cpp 7 
          @brief A trick proposed by Jerry Coffin / Manuel (SO users) to
        

        这确实是我的源代码中的第 7 行。

        【讨论】:

          猜你喜欢
          • 2015-02-07
          • 2021-11-11
          • 1970-01-01
          • 1970-01-01
          • 2018-06-14
          • 2015-09-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多