C++:从文本文件中读取

标签 c++ ifstream

我正在尝试找出读取 .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;
}

关于C++:从文本文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58601912/

相关文章:

c++ - C++中的指针声明

c++ - 我无法让我的程序正确读取输入文件中的值(二维数组)

c++ - std::unordered_multimap 的 bucket 是否只包含具有等效键的元素

javascript - Node-gyp 的先有鸡还是先有蛋的问题 : Pointing to a header file in a dependency

c++ - ifstream 变量可以是全局变量吗?

c++ - ifstream,行尾并移至下一行?

C++,使用 ifstream 读取文件

c++ - 从 C++ 中的多行 txt 文档中读取数字

c++ - 将 C 样式字符串初始化为 NULL 与空字符串之间的区别

c++ - 将 curl_easy 句柄添加到工作中的 curl_multi_handle