我让我的程序从 .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 << " ";
}
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能跳过第一行而不弄乱最后一行?
该while (data.good())是腥。你最终“吃”了一行。参见例如为什么循环条件中的 iostream::eof 被认为是错误的?更多细节。您通常必须getline直接在 中测试结果while,例如
while(getline(data, line)){...}
Run Code Online (Sandbox Code Playgroud)
一种可能的解决方案是逐行读取文件,while(getline(data, line)){...}然后使用 a 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14115 次 |
| 最近记录: |