c++ - C++:从文本文件中读取
问题描述
我试图找出读取 .txt 文件的最佳方法,用逗号分隔信息,行分隔。使用该信息来创建我的股票类的对象。
.txt 文件如下所示:
GOOGL, 938.85, 30
APPL, 506.34, 80
MISE, 68.00, 300
我的股票类构造函数就像 stock(string symbol, double price, int numOfShares);
在我的主程序中,我想设置一个输入文件流,它将读取信息并创建股票类的对象,如下所示:
stock stock1("GOOGL", 938.85, 30);
stock stock2("APPL", 380.50, 60);
我假设我使用 ifstream 和 getline,但不太确定如何设置它。
谢谢!
解决方案
#include <fstream>
#include <string>
#include <sstream>
int main()
{
//Open file
std::ifstream file("C:\\Temp\\example.txt");
//Read each line
std::string line;
while (std::getline(file, line))
{
std::stringstream ss(line);
std::string symbol;
std::string numstr;
//Read each comma delimited string and convert to required type
std::getline(ss, symbol, ',');
std::getline(ss, numstr, ',');
double price = std::stod(numstr);
std::getline(ss, numstr, ',');
int numOfShares = std::stoi(numstr);
//Construct stock object with variables above
stock mystock(symbol, price, numOfShares);
}
return 0;
}
推荐阅读
- node.js - 我如何检查从角度传递到服务器的数据到 node.js
- javascript - 如果长度大于 Jquery 隐藏 Div 元素
- python-3.x - pytorch中使用cnn的二元分类模型
- javascript - 如何遍历包含键和值的数组以在 ReactJS 中发送对 Axios.get 参数的请求?
- javascript - 在使用 JS 的特定行数后显示“阅读更多”按钮
- python - scp 来自 Debian 中 Python 的目录
- django - 如何使用 Django Rest Framework 在同一函数中传递两个查询集
- eclipse - 空项目上的 Eclipse web.xml 中的错误
- javascript - 注销后停用服务人员
- java - 按字段对对象列表进行分组并在其中一个字段中应用二进制函数以使用流 java 8 在一行代码中按总和减少它