首页 > 解决方案 > 文件没有在 C++ 中第二次打开

问题描述

我的代码分为任务 1 和任务 2。我想打开和关闭每个任务以将指针重置到起始位置。我确实尝试fseek(OH-in.txt, 0, SEEK_SET)过而不是第二次打开,但这没有用。

任务无关紧要,只需注意我打开和关闭文件 OH-in.txt 的位置。

该文件只为第一个任务打开(并输出读取的数据)!

这是我的代码

#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
    string collegeName;
    string location;
    int currentEnroll;
    int tuition;
    int numOfSchools = 0;  // edit this in code below
/* 

TASK 1

*/
    // TASK 1: list the schools and the tuition of the schools in Cincinnati with
    // tuition below 20,000
    ifstream file;
    file.open("OH-in.txt");

    vector<string> arr;  // declare array

    // read lines of OH-in.txt
    while (file >> collegeName >> location >> currentEnroll >> tuition) {
        // add collegeName and location to array if true
        if (tuition < 20000 && location == "Cincinnati") {
            collegeName = "(" + collegeName + " $" + to_string(tuition) + ") ";

            arr.push_back(collegeName);
            numOfSchools++;
        }
    }

    for (int i = arr.size() - 1; i >= 0; i--) {
        cout << arr[i];
    }

    cout << numOfSchools << " schools meet this criteria.";
    file.close();
/*


TASK 2

*/
    // TASK 2 Calculate and display the average tuition of schools with more than

    file.open("OH-in.txt");

    vector<string> arr2;

    double avgTuition = 0;
    int expensiveSchools = 0;

    // iterate through the list. If a school with enrollment higher than 10,000 is found, add tuition to total. It will later be divided by the total number of expensive schools.
    while (file >> collegeName >> location >> currentEnroll >> tuition) {
        if (currentEnroll > 10000) {
            avgTuition += tuition;
            expensiveSchools += 1;
        }
        if (collegeName == "BGSU") {
            cout << "BGSU Tuition: " << tuition << endl;
        }
    }
    file.close();
}

标签: c++file

解决方案


推荐阅读