用C ++读取csv文件中的特定行

时间:2013-08-09 20:52:42

标签: c++ csv

我有一个包含许多行数据的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. ");
}

5 个答案:

答案 0 :(得分:0)

这是不可编辑的。

这是你的错吗?

if (endofline = lineNum-1)

lineNum - 1分配给endofline。使用==进行比较。

答案 1 :(得分:0)

保持简单。让一个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。

答案 2 :(得分:0)

如果您只需要读取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;
}

答案 3 :(得分:0)

way to go a specific line in a text file上有一个问题和答案,在那里你可以找到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;
}

答案 4 :(得分:0)

我创建了以下程序,因为我正在练习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;  
}

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

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

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