为什么getline()会切断CSV输入



我试图在C++中读取和解析CSV文件,但遇到了一个错误。

CSV有1-1000行,始终有8列。

一般来说,我想做的是读取csv,只输出符合筛选条件的行。例如,第2列是时间戳,并且仅在特定的时间范围内。

我的问题是我的程序截断了一些行。

在数据位于字符串记录变量中的点上,它不是截断值。当我把它推到int/vvector的映射中时,它的截止点。我是不是做错了什么?

有人能帮我确定真正的问题是什么吗,或者甚至给我一个更好的方法来解决这个问题吗?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <map>
#include "csv.h"
using std::cout; using std::cerr;
using std::endl; using std::string;
using std::ifstream; using std::ostringstream;
using std::istringstream;
string readFileIntoString(const string& path) {
auto ss = ostringstream{};
ifstream input_file(path);
if (!input_file.is_open()) {
cerr << "Could not open the file - '"
<< path << "'" << endl;
exit(EXIT_FAILURE);
}
ss << input_file.rdbuf();
return ss.str();
}
int main()
{
int filterID = 3;
int filterIDIndex = filterID;
string filter = "System";
/*Filter ID's:
0 Record ID
1 TimeStamp
2 UTC
3 UserID
4 ObjectID
5 Description
6 Comment
7 Checksum
*/

string filename("C:/Storage Card SD/Audit.csv");
string file_contents;
std::map<int, std::vector<string>> csv_contents;
char delimiter = ',';
file_contents = readFileIntoString(filename);
istringstream sstream(file_contents);
std::vector<string> items;
string record;
int counter = 0;
while (std::getline(sstream, record)) {
istringstream line(record);
while (std::getline(line, record, delimiter)) {
items.push_back(record);
cout << record << endl;
}

csv_contents[counter] = items;
//cout << csv_contents[counter][0] << endl;
items.clear();
counter += 1;
}

我看不出数据被裁剪的原因,但我对您的代码进行了轻微重构,使用它可能更容易调试问题,如果它不会自行消失的话。

int main()
{
string path("D:/Audit.csv");
ifstream input_file(path);
if (!input_file.is_open()) 
{
cerr << "Could not open the file - '" << path << "'" << endl;
exit(EXIT_FAILURE);
}
std::map<int, std::vector<string>> csv_contents;
std::vector<string> items;
string record;
char delimiter = ';';
int counter = 0;
while (std::getline(input_file, record))
{
istringstream line(record);
while (std::getline(line, record, delimiter))
{
items.push_back(record);
cout << record << endl;
}
csv_contents[counter] = items;
items.clear();
++counter;
}
return counter;
}

我试过你的代码,(在修复了分隔符后(没有问题,但我只有三行数据,所以如果是内存问题,它不太可能显示出来。

最新更新