【发布时间】:2022-10-17 16:39:57
【问题描述】:
我认为我已经正确地做到了这一点,并且我引用了其他有效的 C++ 代码,但我没有得到正确的输出。这是我想要做的。我正在尝试读取一个 EXCEL 文件并解析股票信息并将它们添加到他们自己的每个对象中,以便它像这样存储:
Stock recordedStock(symbol, bidPrice, askPrice, bidSize, askSize); //Creating object Stock with attributes that were read
现在我创建了 Excel 文件,它非常简单。每列是一个股票代码、bidPrice、askPrice、bidSize 和 askSize。此 Excel 工作表没有标题。这是它的样子:
由于某种原因,我实现的功能没有正确输出。它在第二行输出亚马逊股票,第一行每个问题只显示 35 个,没有捕获其他股票信息。这是我的实现:
void StockParser::on_market_data(const char* filename) {
string row; // string used for row read from each line
string symbol; //Stock object attributes that will store attributes parsed
double bidPrice;
double askPrice;
int bidSize;
int askSize;
string temp;
ifstream inputFile;
inputFile.open(filename);
while (getline(inputFile, row)) { //loop until it reaches the end of the data
stringstream rowStream(row); //This stream is used to read the row of data and put them in the assigned attributes
getline(inputFile, symbol, ',');
getline(inputFile, temp, ',');
bidPrice = stod(temp);
getline(inputFile, temp, ',');
askPrice = stod(temp);
getline(inputFile, temp, ',');
bidSize = stoi(temp);
getline(inputFile, temp, ',');
askSize = stoi(temp);
Stock recordedStock(symbol, bidPrice, askPrice, bidSize, askSize); //Creating object Stock with attributes that were read
stockMap.insert(pair<string, Stock>(symbol, recordedStock)); /* Inserting symbol and recordedStock as a pair into the map.
Now you can obtain Stock attributes with the key symbol*/
}
inputFile.close();
任何帮助表示赞赏。我不确定这里发生了什么。这是我练习如何为即将到来的工作面试解析文件。感谢您的时间。
【问题讨论】:
-
您正在阅读 Excel 文件还是 CSV(逗号分隔值)?
-
绝对看起来像 CSV。
-
我很好奇如何在没有任何库的情况下阅读
.xls或.xlsx文件;这就是我问的原因。 -
在 Internet 上搜索“C++ 读取 csv 文件”或使用调试器查找程序问题。
-
*.xlsx 文件基本上是 zip 文件。没有图书馆或很多更多代码,您将无法仅阅读它们。
标签: c++ parsing ifstream getline