Reading in from a CSV data file, erroring out when trying to pull in only what I need
我试图从一个csv文件中提取两列数据并转储其余的数据。
我收到的错误是:
STD:STD::Basic SistReMa>和((?)STORACKSTD::Basic SistReMa:>:(* ELEM*,STD::SRIGHEZESS)
C38 67:"STD::Basic IsReRAM>::Read::非标准语法;使用‘and’"来创建指向成员的指针
数据的格式如下:
1928,44.50%,……
我希望1928年分配到data.year,44.50%分配到data.yield,但不包括百分号。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | bool ReadData(MyData &data) { //Variable for reading data into file stream ifstream inFile; string trash; char junk; cout <<" Reading file . . ."; //Open data file inFile.open("Data.csv"); //Read the first 18 lines, and throw it away for (int i = 0; i < 18; ++i) { getline(inFile, trash); } //Read the necessary data into the arrays for (int i = 0; i < SIZE; ++i) { //=============================================================== //This line is throwing 2 errors //Goal: read first column of a simple integer into data.year, discard the comma, then read the second column of a double into data.yield, discard the percentage sign. infile.ignore(); to clear cin stream, getline(inFile, trash) to discard remainder of the lines. inFile.read >> data.year[i] >> junk >> data.yield[i] >> junk >> trash >> endl; //=============================================================== inFile.ignore(); getline(inFile, trash); } //Return false if file could not be opened if (!inFile) { cout <<" Technical error! The file could not be read."; return false; } else { cout <<" File opened successfully!"; return true; } inFile.close(); } struct MyData { int year[SIZE]; int yield[SIZE]; double minYield; double maxYield; double avgYield; }; |
我哪里出错了?
1 | inFile.read >> data.year[i] >> junk >> data.yield[i] >> junk >> trash >> endl; |
我建议您尝试一种不同的方法:读取整行,并使用explode函数来检索单个元素。例如,PHP函数的C++中是否有一个等价物?
第一个问题是一行一行地读取一个文件的常量次数,但是您永远不知道文件的大小。所以,你应该在你的
1 2 3 4 5 6 7 8 9 10 11 12 13 | for (int i = 0; i < SIZE && std::getline(infile, line); ++i) { std::stringstream linestream(line); std::string year, yield; getline(linestream,year,','); getline(linestream,yield,','); yield.erase(std::remove(yield.begin(), yield.end(), '%'), yield.end()); // remove % myData.year[i] = std::stoi( year ); // string to int myData.yield[i] = std::stod( year ); // string to double } |
附言:别忘了包括