gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:55:47 25 4
gpt4 key购买 nike

我让我的程序从 .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())有腥味。你最终“吃掉”了一行。参见例如Why is iostream::eof inside a loop condition considered wrong?更多细节。您通常必须测试 getline 的结果直接在 while , 喜欢

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;
}
}

关于c++跳过csv文件的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com