【发布时间】:2018-04-09 05:51:42
【问题描述】:
我正在尝试创建一个重复菜单,如果程序无法打开文件,该菜单将允许用户重新输入文件名。
现在,如果我输入现有文件的名称,它可以正常工作,但如果文件不存在,它会打印“找不到文件”,然后执行程序的其余部分。我是文件流的新手,这里的大部分代码都是通过引用找到的。我对到底发生了什么以及处理这种情况的最佳方法有点迷茫。任何指导将不胜感激。
typedef istream_iterator<char> istream_iterator;
string fileName;
ifstream file;
do {
cout << "Please enter the name of the input file:" << endl;
cin >> fileName;
ifstream file(fileName.c_str());
if (!file) {
cout << "File not found" << endl;
}
} while (!file);
std::copy(istream_iterator(file), istream_iterator(), back_inserter(codeInput));
【问题讨论】:
-
您在循环中声明了一个与外部文件同名的变量。将
ifstream file (fileName.c_str());更改为file = std::ifstream(fileName);应该没问题。