如何在函数中读取用户输入的文件名?解决跨函数调用时文件内容加载失败问题
问题分析与解决办法
咱们先拆解下你代码里的核心问题:你在inputfilename()里创建的ifstream file是局部变量,这个函数执行完毕后,这个file对象就会被销毁,它打开的文件也会自动关闭。而getColRow()里的ifstream file是另一个完全独立的局部对象,根本没和你输入的文件名关联上,自然读不到任何内容。
下面给你两种可行的修复方案:
方案一:让inputfilename返回文件名(推荐,职责更清晰)
把获取文件名的逻辑和文件操作分开,inputfilename只负责拿到正确的文件名,然后在getColRow里用这个文件名打开文件读取数据:
#include <iostream> #include <fstream> #include <string> using namespace std; // 只负责获取并返回带后缀的文件名 string inputfilename() { string name; getline(cin, name); name.append(".txt"); return name; } void getColRow(int &row, int &col) { string filename = inputfilename(); ifstream file(filename); // 一定要处理文件打开失败的情况,避免后续使用未初始化的变量 if (!file) { cout << "Error File" << endl; row = 0; col = 0; return; } file >> col; file >> row; file.close(); } int main() { int col, row; getColRow(row, col); cout << col << ":" << row << endl; return 0; }
方案二:传递ifstream引用给inputfilename
如果不想拆分逻辑,可以把getColRow里的ifstream对象以引用的方式传给inputfilename,让它负责打开文件:
#include <iostream> #include <fstream> #include <string> using namespace std; // 接收ifstream的引用,负责打开指定文件 void inputfilename(ifstream &file) { string name; getline(cin, name); name.append(".txt"); file.open(name); if (!file) { cout << "Error File" << endl; } } void getColRow(int &row, int &col) { ifstream file; inputfilename(file); if (!file) { row = 0; col = 0; return; } file >> col; file >> row; file.close(); } int main() { int col, row; getColRow(row, col); cout << col << ":" << row << endl; return 0; }
额外提醒
不管用哪种方案,都要记得处理文件打开失败的情况——不能只输出错误信息,还要给row和col设置合理的默认值,否则后续使用这两个变量会出现未定义行为。
内容的提问来源于stack exchange,提问作者Wu Hee
相关产品推荐
相关产品推荐

