c++ - 文件没有在 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();
}
解决方案
推荐阅读
- python - 使用 Sentence Tokenizer 后从列表列表中选择子列表
- java - Java 二维数组值和for循环问题
- msbuild - MSBuild 任务和 Roslyn
- wpf - WPF,在TextBox中输入文本时,字符从右到左运行
- java - 在 C# 与 Java 中实现接口的不同方法
- swift - 为什么我不断将无法识别的选择器发送到实例 0x7f8a1b437780
- mysql - phpMyAdmin 和 mysql 保留字
- android - 设备组消息 (FCM) 限制
- selenium - selenium - 找到一个 href 链接 - 无法找到带有链接文本的元素
- sql - 如何使用输出将行从表插入到表