我試圖用 C 讀取和決議我的 CSV 檔案,但遇到了錯誤。
CSV 有 1-1000 行,總是 8 列。
通常,我想做的是讀取 csv 并僅輸出與過濾器標準匹配的行。例如,第 2 列是時間戳,并且僅在特定時間范圍內。
我的問題是我的程式切斷了一些行。在資料位于字串記錄變數中的點處,它不會被截斷。一旦我將它推入 int/vector 的映射中,它就會被截斷。我在這里做錯了嗎?
有人可以幫我確定真正的問題是什么,或者甚至可以給我一個更好的方法來做到這一點?
#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;
}
uj5u.com熱心網友回復:
我看不出你的資料被裁剪的原因,但我稍微重構了你的代碼,使用它可能更容易除錯問題,如果它不只是自行消失。
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;
}
我已經嘗試了你的代碼并且(在修復了分隔符之后)沒有問題,但是我只有三行資料,所以如果它是一個記憶體問題,它就不太可能顯示出來。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403371.html
標籤:
上一篇:以自定義字串格式讀取CSV檔案
下一篇:CSV資料的平均值
