我让我的程序从.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 << " ";
}
}
如果不弄乱最后一行,我该怎么做才能跳过第一行呢?
答案 0 :(得分:3)
while (data.good())
很可疑。你最终&#34;吃&#34;还有一行。参见例如Why is iostream::eof inside a loop condition considered wrong?了解更多详情。您通常必须直接在getline
中测试while
的结果,例如
while(getline(data, line)){...}
一种可能的解决方案是逐行阅读文件while(getline(data, line)){...}
,然后使用stringstream(line)
,对于每一行,再次使用getline
进行解析,现在由{{1}分隔}。要跳过第一行,请先执行,
,然后使用getline(data, line);
进行跟进。下面是一个简单的例子:
while(getdata(data, line)){ /* process line */}