所以我基本上需要我的程序来打开一个文件并做一些事情。当程序要求用户输入文件名,并且用户第一次正确输入文件名时,操作有效。但是,如果用户输入了错误的名称,程序会提示“名称无效,请重试”,但即使用户输入的名称正确,它也永远无法打开文件。这是代码:
ifstream read_file(file.c_str());
while(true)
{
if(!(read_file.fail()))
{
...
}
else
{
cout << "Either the file doesn't exist or the formatting of the file is incorrect. Try again.\n>";
}
cin >> file;
ifstream read_file(file.c_str());
}
问题是什么,有什么想法吗?谢谢
最佳答案
您在循环内重新声明 read_file,但循环顶部的代码始终在循环外使用 read_file。
这就是你想要的:
ifstream read_file(file.c_str());
while(true)
{
if(!(read_file.fail()))
{
...
}
else
{
cout << "Either the file doesn't exist or the formatting of the file is incorrect. Try again.\n>";
}
cin >> file;
read_file.open(file.c_str()); /// <<< this has changed
}
关于C++ 打开文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9154999/