[英]Why does getline() cut off CSV Input?
我試圖在 C++ 中讀取和解析我的 CSV 文件並遇到錯誤。
CSV 有 1-1000 行,總是 8 列。
一般來說,我想做的是僅閱讀與過濾器標准匹配的 csv 和 output 行。 例如,第 2 列是時間戳,並且僅在特定時間范圍內。
我的問題是我的程序切斷了一些行。 在數據位於字符串記錄變量中的點處,它不是截止點。 一旦我將它推入 int/vector 的 map,它的截止值。 我在這里做錯了嗎?
有人可以幫助我確定問題的真正含義,或者甚至給我一個更好的方法來做到這一點嗎?
#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;
}
我已經嘗試過您的代碼並且(在修復分隔符之后)沒有問題,但我只有三行數據,所以如果它是 memory 問題,它不太可能顯示出來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.