繁体   English   中英

c ++跳过csv文件的第一行

[英]c++ Skip first line of csv file

我让程序从.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)){...}逐行读取文件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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM