C++初级读本5版1.23从文件流中读取

C++ Primer 5 ed.1.23 Reading from a file stream

本文关键字:文件 读取 初级读本 5版 C++      更新时间:2023-10-16

我通过学习C++初级读本第5版自学C++,我提出了练习1.23,其中规定:编写一个程序,读取几个事务,并计算每个ISBN发生的事务数量。

我曾想过使用变量来存储事务信息,但在实际场景中,这是不可扩展的。我做了一些研究,并试图通过Fstream标头读取文本文件。

我的问题是,当使用fstream时,我如何让它在文本文件中查找并返回该特定ISBN编号的条目数?

我的想法正确吗?有没有更好的方法来做到这一点?

像这样使用fstream只是一个基本想法:

#include <iostream>
#include <fstream>
#include <stdexcept>
std::ifstream file("file_name.txt");
std::string ISBN("99959");
if (!file)
throw std::runtime_error("Open file error");
std::string line; // Or whatever the data is in the file
int count = 0;
while (file) 
{
std::getline(file, line);
if (line.find(ISBN) == std::string::npos)
++count;
}