我正在尝试创建一个重复菜单,允许用户在程序无法打开文件时重新输入文件名。
现在,如果我输入现有文件的名称,它可以正常工作,但如果该文件不存在,它会打印“未找到文件”,然后执行程序的其余部分。我是文件流的新手,这里的大部分代码都是通过引用找到的。我对到底发生了什么以及处理这种情况的最佳方法有点迷茫。任何指导将不胜感激。
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));
最佳答案
构造对象后 file
将永远存在,所以你的循环条件总是失败。将条件更改为文件是否未正常打开。
do {
...
}
while (!file.is_open())
关于c++ - 具有重复输入的文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49726344/