具有重复输入的文件流
File stream with repeating input
我正在尝试创建一个重复菜单,允许用户在程序无法打开文件时重新输入文件名。
现在,如果我输入现有文件的名称,它可以正常工作,但如果该文件不存在,它会打印 "File not found",然后执行程序的其余部分。我是文件流的新手,这里的大部分代码都是通过引用找到的。我对到底发生了什么以及处理这种情况的最佳方法有点迷茫。任何指导将不胜感激。
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());
我正在尝试创建一个重复菜单,允许用户在程序无法打开文件时重新输入文件名。
现在,如果我输入现有文件的名称,它可以正常工作,但如果该文件不存在,它会打印 "File not found",然后执行程序的其余部分。我是文件流的新手,这里的大部分代码都是通过引用找到的。我对到底发生了什么以及处理这种情况的最佳方法有点迷茫。任何指导将不胜感激。
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());