c++ - 将文件传递给几个函数

标签 c++

我正在主函数中打开一个文件。我想将此文件传递给几个函数,但看起来第一个调用的函数正在清除此文件。 这是一个文件:

1 5 6 8
6 5
1
2 6 8
6 7 5 1 2 4

第一个函数计算文件中的行数。第二个函数计算单个数字的数量。

int countTransactions(ifstream &dataBaseFile) {
    int numOfTransactions = 0;
    string line;

    while(getline(dataBaseFile, line))
        numOfTransactions++;

    cout << "countTransaction" << endl;
    cout << numOfTransactions << endl;
    return numOfTransactions;
}

void countItems(ifstream &dataBaseFile) {
    map<int, int> items;
    map<int, int>::iterator it;
    int item;

    while(!dataBaseFile.eof()) {
        dataBaseFile >> item;

        it = items.find(item);
        if(it != items.end()) {
            it->second++;
            continue;
        } else items.insert(make_pair(item, 1));
    }

    for(it = items.begin(); it != items.end(); it++)
        cout << it->first << " => " << it->second << endl;
}

int main() {
    ifstream dataBaseFile("database3.txt", ios::in);

    if(!dataBaseFile.good()) {
        cout << "Failure while opening file";
        exit(1);
    }

    countItems(dataBaseFile);
    countTransactions(dataBaseFile);

    dataBaseFile.close();
}

这是一个输出:

countTransation
5
countItems

最佳答案

std::ifstream有一个状态,这意味着您对其应用的操作会影响 future 操作的结果。例如,流有一个阅读位置。当您从流中读取内容时,读取位置会根据您已读取的数据量前进。

当你通过 dataBaseFilecountItems ,它读取整个文件,并将读取位置一直推进到末尾。当您调用 countTransactions 时,这就是职位所在的位置。 , 所以它认为没有什么可读的。

Resetting the read position back to zero将解决这个问题:

countItems(dataBaseFile);
dataBaseFile.clear(); // To clear out EOF
dataBaseFile.seekg(0, ios::beg);
countTransactions(dataBaseFile);

但是,这在性能方面并不理想,因为您最终会多次读取文件。当文件很小时,最好将整个文件读入内存,例如进入std::vector<std::string> ,以及使用内存中的表示形式来实现更快的访问。

关于c++ - 将文件传递给几个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45167878/

相关文章:

c++ - 如何获得在 SFML 中按下按键后耗时?

c++ - 如何将 std::bind 与 compose2 一起使用?

c++ - 类型转换基类问题

c++ - consteval 函数是否允许依赖于函数参数的模板参数?

c++ - 堆栈分配的 RAII 对象与 DI 原则

c++ - 在构造函数中为类名添加和省略模板参数之间的区别

c++ - 如何从双端队列中提取元素?

c++ - 删除 [] 时发生堆损坏错误

c++ - 区分具有类型特征的结构

c++ - 对 OpenMP 中静态调度开销的影响