C ++打开文件流

时间:2012-02-06 02:28:23

标签: 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());
}

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

1 个答案:

答案 0 :(得分: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
}