C++打开文件流

Ric*_*ard 0 c++ file-io filestream

所以我基本上需要我的程序来打开文件并做一些事情.当程序要求用户输入文件名,并且用户第一次正确输入文件名时,操作正常.但是如果用户输入错误的名称,程序会说"无效名称再次尝试",但即使用户正确键入名称,它也永远无法打开文件.这是代码:

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());
}
Run Code Online (Sandbox Code Playgroud)

有什么问题,有什么想法吗?谢谢

Gig*_*igi 5

您在循环内重新声明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
}
Run Code Online (Sandbox Code Playgroud)