我通过阅读ISBN入门第五版来自学C++,我已经完成了练习1.23,其中规定:编写一个程序,读取多个事务,并计算每个C++发生了多少事务。
我考虑过使用变量来存储事务信息,但在实际场景中,这是不可伸缩的。我做了一些研究,并且一直在尝试通过Fstream头文件读取文本文件。
我的问题是,当使用fstream时,我如何让它在文本文件中查找,并返回该特定ISBN号有多少个条目?
我的想法是正确的吗?有没有更好的方法来完全做到这一点?
发布于 2020-07-09 06:06:51
像这样使用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;
}https://stackoverflow.com/questions/62803996
复制相似问题