如何读取不带换行符的CSVloggingCRLF“\ r \ n”?

即时通讯非常新的C ++,并试图找出如何读取CSV文件到一个向量。 到目前为止,一切都很好,除了我不知道如何避免在每个CSVlogging结束的换行符。

inheritance人我的代码:

#include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> // stream input operator overloaded to read a list of CSV fields std::istream &operator >> (std::istream &ins, std::vector<std::string> &record) { record.clear(); // read the entire line into a string std::string line; std::getline(ins, line); // using a stringstream to separate the fields out of the line std::stringstream ss(line); std::string field; while (std::getline(ss, field, ';')) { // add the converted field to the end of the record record.push_back(field); } return ins; } // stream input operator overloaded to read a list of CSV fields std::istream &operator >> (std::istream &ins, std::vector<std::vector<std::string>> &data) { data.clear(); // add results from record into data std::vector<std::string> record; bool empty; while (ins >> record) { // check if line has a price for (unsigned i = 0; i < record.size(); i++) { std::stringstream ss(record[2]); int price; if (ss >> price) { empty = true; } else { empty = false; } } if (empty == true) { data.push_back(record); } } return ins; } int main() { // bidemensional vector for storing the menu std::vector<std::vector<std::string>> data; // reading file into data std::ifstream infile("test.csv"); infile >> data; // complain if theres an error if (!infile.eof()) { std::cout << "File does not excist." << std::endl; return 1; } infile.close(); for (unsigned m = 0; m < data.size(); m++) { for (unsigned n = 0; n < data[m].size(); n++) { std::string recordQry; recordQry += "'" + data[m][n] + "', "; std::cout << recordQry; } std::cout << std::endl; } return 0; } 

test.csv包含:

 CODE;OMSCHRIJVING; PRIJS ;EXTRA;SECTION A1;Nasi of Bami a la China Garden; 12,00 ;ja;4 A2;Tjap Tjoy a la China Garden; 12,00 ;ja;1 A3;Tja Ka Fu voor twee personen; 22,50 ;ja;1 

尝试:

 while (std::getline(ss, field, ';')) { // add the converted field to the end of the record record.push_back(field.erase(s.find('\r')); } //record.push_back(field.erase(s.find('\r')); return ins; 

那么我会删除我的答案,但决定重新提交一个,因为无论所有关于getline的事实,你确实知道你有问题。 在其他答案的意见中,我注意到你提到它最初是一个excel文件。 那么,至less在某些情况下,微软以\r\n结尾。 那可能是为什么? getline仍然会放弃\n但是您仍然可以回车。 如果是这种情况,你需要使用我之前分享的方法之一。 我希望我已经赎回自己..

我检查了使用\r\n写入文件,是的,它会离开\r 。 我在debugging中看过它,甚至当我再次使用getline来提取它留在string中的值时。 当它打印到控制台时,它将打印浮动在第一个字母下的光标值。

微软显然使用这种风格来向后兼容老式机器,这需要两个独立的function – 一个是将头部返回到左边缘,另一个是卷起纸张。 这听起来像你正在经历的行为?