跳过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)){...}
逐行读取文件,然后使用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++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 正在将csv文件读取为双精度矢量
- 从C++dll访问C#中的一行主要参数
- 在C++中,我如何接受不同于同一行的用户输入
- 如何从一行中读取特定数量的字符?(C++)
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 如何选择在 csv 文件中输出的位置
- 有没有办法在一行中填充矢量图
- 需要将一行代码从C++ Qt翻译成PyQt
- 为什么如果我添加这一行,我的程序会不断询问值
- 如何使代码打印文本文件中的第一行?
- 为什么仅在CSV文件中打印第一行
- 如何在用户输入值后写入.csv文件的下一行,而不会覆盖以前的值?
- 用C++覆盖CSV文件中的一行
- 跳过csv文件的第一行
- 有效地读取csv文件的最后一行
- 如何处理csv文件输入流,我需要将文件的每一行中的数据划分为6个不同的变量(类型字符串和int)