具有重复输入的文件流
File stream with repeating input
我正在尝试创建一个重复菜单,如果程序无法打开文件,该菜单将允许用户重新输入文件名。
现在,如果我输入现有文件的名称,它可以正常工作,但如果该文件不存在,它会打印"找不到文件",然后执行程序的其余部分。我是文件流的新手,这里的大部分代码都是通过引用找到的。我有点迷茫到底发生了什么,以及处理这种情况的最佳方法是什么。任何指导将不胜感激。
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())
此代码将起作用。
do {
std::cout << "Please enter the name of the input file:" << std::endl;
std::cin >> fileName;
file = std::ifstream(fileName.c_str());
if (!file) {
std::cout << "File not found" << std::endl;
}
} while (!file);
您的错误是文件变量有 2 个定义。while (!file)
中使用的变量是在 do-while 循环外部定义的变量,默认情况下,其有效状态设置为 true。
除了@acraig5075答案:
先写一个类型,然后写一个变量名(ifstream file
(就是创建一个新变量。显然你知道这一点,但是如果你在循环中再次使用相同的名称,它会创建一个新的和不同的变量。
ifstream file; // a unique variable
...
do {
...
ifstream file(fileName.c_str()); // another unique variable
。因此,将循环内的用法更改为:
file.open(fileName.c_str());
相关文章:
- C++文本文件输入
- C++ 中文件输入输出中的长长 v/s int
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 用空格填充 2D 数组(从文件输入)
- 流对象来表示文件输入,然后是标准输入?
- 用精神解析文件输入
- 从文件输入和输出
- 来自文本文件输入 c++ 的向量
- 如何通过键盘或分数文件输入分数
- 了解文件输入和输出,我可以写入文件,但无法从文件打印
- 词频程序 - 文件输入太大?
- 尝试从 csv 文件输入大量数据时出错
- 如何将文件从文件输入到C 中的矩阵中
- 如何从Windows CMD运行可执行文件并将其传递给文件输入的参数参数和重定向
- 如何解析文本文件并使用构造函数中的文件输入来创建对象的容器
- 这是读取文件输入的正确方法吗?
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- 如何创建一个具有空值、递减编号系统和.txt文件输入值的二维阵列网格
- C 文件输入流循环问题
- 使用对输入整数的文件输入