首页 > 解决方案 > 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,但不太确定如何设置它。

谢谢!

标签: c++ifstream

解决方案


#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;
}

推荐阅读