跳过csv文件的第一行

c++ Skip first line of csv file

本文关键字:一行 csv 文件 跳过      更新时间:2023-10-16

我让我的程序从.csv文件中读取并输出数据,但我不希望它输出第一行。我试过用getline(data, line);stream.ignore ( std::numeric_limits<std::streamsize>::max(), 'n' );。虽然它确实跳过第一行,但最后两行打印两次并且混淆了。

string ID;
string sentenceIn;
string servedIn;
int sentence;
int served;
string lastName;
string firstName;
vector<string> idNum;
vector<string> sentenceLen;
vector<string> servedTime;
vector<string> lastNameIn;
vector<string> firstNameIn;

ifstream data("prisoner_data.csv");
if (data.is_open())
{
    cout << "File opened successfully." << endl << endl;
    while (data.good()) // !someStream.eof()
    {
        getline(data, ID, ',');
        cout << ID << "  ";
        idNum.push_back(ID);
        getline(data, sentenceIn, ',');
        cout << sentenceIn << "  ";
        sentenceLen.push_back(sentenceIn);
        istringstream(sentenceIn) >> sentence;
        getline(data, servedIn, ',');
        cout << servedIn << "  ";
        servedTime.push_back(servedIn);
        istringstream(servedIn) >> served;
        getline(data, lastName, ',');
        lastNameIn.push_back(lastName);
        cout << lastName << "  ";
        getline(data, firstName, ',');
        firstNameIn.push_back(firstName);
        cout << firstName << "  ";
    }
}

我怎么做才能跳过第一行而不弄乱最后一行?

while (data.good())有问题。最后你又"吃"了一行。为什么循环条件中的iostream::eof被认为是错误的?了解更多详情。通常必须直接在while中测试getline的结果,如

while(getline(data, line)){...}

一个可能的解决方案是使用while(getline(data, line)){...}逐行读取文件,然后使用stringstream(line),对于每一行,再次使用getline解析,现在用,分隔。要跳过第一行,只需在之前执行getline(data, line);,然后执行while(getdata(data, line)){ /* process line */}。下面是一个简单的例子:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cstdlib>
int main()
{     
    std::ifstream data("prisoner_data.csv");
    if (!data.is_open())
    {
        std::exit(EXIT_FAILURE);
    }
    std::string str;
    std::getline(data, str); // skip the first line
    while (std::getline(data, str))
    {
        std::istringstream iss(str);
        std::string token;
        while (std::getline(iss, token, ','))
        {   
            // process each token
            std::cout << token << " ";
        }
        std::cout << std::endl;
    }
}