fstream对象重复使用需注意clear的调用,否则会出错

本文探讨了ifstream对象在C++中重复使用时遇到的问题及解决办法。重点介绍了在使用ifstream对象打开多个文件时,若不调用clear函数清除状态标志可能会导致的错误行为,并通过实例对比展示了正确使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 ifstream对象如果重复使用,须注意在使用之前先调用clear函数,否则会出错
表现为:
代码一:
====================================================
 ifstream fin("x.txt");
 if(fin.fail())
 {
  cout << " failed to open x.txt" << endl;
 }
 fin.close();
 fin.open("y.txt");
 if(fin.fail())
 {
  cout << " failed to open y.txt" << endl;
  //
  goto EXIT;
 }
 
 cout <<" succeed"<< endl;
EXIT:
 fin.close();
============================================
输出: failed to open y.txt
============================================
代码二:
============================================
 ifstream fin("y.txt");
 if(fin.fail())
 {
  cout << " failed to open y.txt" << endl;
 }
 fin.close();

// fin.clear(); //注意添加clear
 fin.open("x.txt");
 if(fin.fail())
 {
  cout << " failed to open x.txt" << endl;
  //
  goto EXIT;
 }
 
 cout <<" succeed"<< endl;
EXIT:
 fin.close();
=======================================
输出: failed to open y.txt
      failed to open x.txt
=======================================
代码二打开x.txt失败的
原因: 跟踪代码实现发现,在open成功后不会对 fstream中状态进行操作,而open失败的话会设置_MyState为failbit,并且在close操作时如果本身是空文件,也会设置state为failbit,这样造成一次失败之后的其他很多操作都是失败的,因为很多fstream操作会先判断state;

而clear函数是将fstream状态重置为goodbit

所以代码二在添加了clear代码后正常

 

TODO:

STL的文件流类挺复杂的——》《源码分析》TO SEE
   

#include <iostream> // 输入输出流库,用于cin/cout操作 #include <string> // 字符串处理库 #include <cctype> // 字符处理函数库(虽然本例未直接使用,但通常用于输入验证) using namespace std; // 使用标准命名空间,避免重复写std:: // 课题类 - 表示单个课题的实体 class Topic { public: string title; // 课题标题(字符串类型) bool isSelected; // 课题是否已被选择(布尔类型) string selectedBy; // 选择该课题的学生姓名(字符串类型) // 构造函数 - 创建课题对象时自动调用 Topic(string t) : title(t), isSelected(false), selectedBy("") {} // 参数t: 传入的课题标题 // : 后是成员初始化列表 // title(t) - 将成员title初始化为传入的t // isSelected(false) - 初始状态设为未选择 // selectedBy("") - 初始选择者设为空字符串 }; // 类定义结束 // 课题管理系统类 - 管理课题集合 class TopicManager { private: Topic** topics; // 指向课题指针数组的指针(动态二维数组) int capacity; // 当前数组的容量(可容纳的最大课题数) int size; // 当前实际存储的课题数量 // 调整数组容量的私有方法 void resize(int newCapacity) { // 创建新容量的指针数组 Topic** newTopics = new Topic*[newCapacity]; // 将原数组内容复制到新数组 for (int i = 0; i < size; ++i) { newTopics[i] = topics[i]; // 复制指针(浅拷贝) } // 释放原数组内存 delete[] topics; // 先删除指针数组 topics = newTopics; // 将topics指向新数组 capacity = newCapacity; // 更新容量值 } public: // 构造函数 - 初始化管理系统 TopicManager() : topics(nullptr), capacity(0), size(0) {} // 初始化列表: // topics(nullptr) - 初始化为空指针 // capacity(0) - 初始容量为0 // size(0) - 初始课题数为0 // 析构函数 - 对象销毁时自动调用,释放内存 ~TopicManager() { // 遍历所有课题对象,释放每个课题的内存 for (int i = 0; i < size; ++i) { delete topics[i]; // 删除每个课题对象 } delete[] topics; // 删除课题指针数组 } // 增加课题的公共方法 void addTopic(string title) { // 检查是否需要扩容 if (size >= capacity) { // 计算新容量:初始为2,之后倍增 int newCapacity = (capacity == 0) ? 2 : capacity * 2; resize(newCapacity); // 调用扩容方法 } // 在数组末尾创建新课题 topics[size] = new Topic(title); // 动态分配内存 size++; // 课题数量增加 cout << "课题已添加: " << title << endl; // 操作反馈 } // 删除课题的公共方法 void deleteTopic(int index) { // 检查索引有效性 if (index >= 0 && index < size) { cout << "课题已删除: " << topics[index]->title << endl; // 反馈 delete topics[index]; // 释放该课题的内存 // 移动后续元素填补空缺 for (int i = index; i < size - 1; ++i) { topics[i] = topics[i + 1]; // 指针前移 } size--; // 课题数量减少 } else { cout << "无效的课题索引。" << endl; // 错误提示 } } // 修改课题的公共方法 void modifyTopic(int index, string newTitle) { // 检查索引有效性 if (index >= 0 && index < size) { topics[index]->title = newTitle; // 更新标题 cout << "课题已修改: " << newTitle << endl; // 反馈 } else { cout << "无效的课题索引。" << endl; // 错误提示 } } // 显示所有课题的公共方法 void displayTopics() { cout << "当前课题列表:" << endl; // 标题 // 遍历所有课题 for (int i = 0; i < size; ++i) { // 输出序号和标题 cout << i + 1 << ". " << topics[i]->title; // 如果课题已被选择,显示选择者信息 if (topics[i]->isSelected) { cout << " (已选择 by " << topics[i]->selectedBy << ")"; } cout << endl; // 换行 } } // 选择课题的公共方法 void selectTopic(int index, string studentName) { // 检查索引有效性 if (index >= 0 && index < size) { // 检查课题是否已被选择 if (!topics[index]->isSelected) { topics[index]->isSelected = true; // 标记为已选择 topics[index]->selectedBy = studentName; // 记录选择者 cout << "你已选择课题: " << topics[index]->title << endl; // 反馈 } else { // 课题已被选择时显示选择者信息 cout << "该课题已被选择 by " << topics[index]->selectedBy << endl; } } else { cout << "无效的课题索引。" << endl; // 错误提示 } } // 查看已选课题的公共方法 void viewSelectedTopics() { cout << "已选课题列表:" << endl; // 标题 // 遍历所有课题 for (int i = 0; i < size; ++i) { // 只显示已被选择的课题 if (topics[i]->isSelected) { // 输出课题标题和选择者 cout << topics[i]->title << " by " << topics[i]->selectedBy << endl; } } } }; // 菜单显示函数 void menu() { // 输出菜单选项 cout << "Menu:" << endl; cout << "1. 添加课题" << endl; cout << "2. 删除课题" << endl; cout << "3. 修改课题" << endl; cout << "4. 显示所有课题" << endl; cout << "5. 选择课题" << endl; cout << "6. 查看已选课题" << endl; cout << "7. 退出系统" << endl; } // 获取有效整数输入的函数 int getValidIntInput() { int value; // 存储输入值的变量 // 循环直到获得有效输入 while (!(cin >> value)) { cout << "输入无效,请重新输入: "; // 错误提示 cin.clear(); // 清除错误状态 cin.ignore(10000, '\n'); // 忽略缓冲区中的错误输入 } return value; // 返回有效整数 } // 主函数 - 程序入口点 int main() { TopicManager manager; // 创建课题管理器对象 int choice; // 存储用户选择的变量 // 主循环 do { menu(); // 显示菜单 cout << "请选择操作: "; choice = getValidIntInput(); // 获取有效整数输入 cin.ignore(); // 忽略换行符,防止影响后续输入 // 根据用户选择执行操作 switch (choice) { case 1: { // 添加课题 string title; cout << "请输入课题名称: "; getline(cin, title); // 读取整行输入 manager.addTopic(title); // 调用添加方法 break; } case 2: { // 删除课题 cout << "请输入要删除的课题索引: "; int index = getValidIntInput(); // 获取索引 manager.deleteTopic(index - 1); // 调用删除方法(索引-1转换为0-based) break; } case 3: { // 修改课题 cout << "请输入要修改的课题索引: "; int index = getValidIntInput(); // 获取索引 cin.ignore(); // 清除换行符 string newTitle; cout << "请输入新的课题名称: "; getline(cin, newTitle); // 读取新标题 manager.modifyTopic(index - 1, newTitle); // 调用修改方法 break; } case 4: // 显示所有课题 manager.displayTopics(); // 调用显示方法 break; case 5: { // 选择课题 cout << "请输入要选择的课题索引: "; int index = getValidIntInput(); // 获取索引 cin.ignore(); // 清除换行符 string studentName; cout << "请输入你的名字: "; getline(cin, studentName); // 读取学生姓名 manager.selectTopic(index - 1, studentName); // 调用选择方法 break; } case 6: // 查看已选课题 manager.viewSelectedTopics(); // 调用查看方法 break; case 7: // 退出系统 cout << "退出系统。" << endl; // 退出提示 break; default: // 无效选择处理 cout << "无效的选择。" << endl; break; } cout << endl; // 添加空行,使界面更清晰 } while (choice != 7); // 当选择7时退出循环 return 0; // 程序正常结束 }
最新发布
06-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值