C++ 打开文件流

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

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

最佳答案

您在循环内重新声明 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/

相关文章:

c++ - 使用设备文件符号链接(symbolic link)查找总线号和设备号

c++ - 对 `MyClass::staticMemeber' 的 undefined reference

java - 第二种方法调用比第一种方法花费的时间少得多

c++ - 在 C++ 中按字符读取输入文件时的换行符

c - while(!feof(file)) 读取额外的行

c++ - 如何访问第i个 map 成员?

c++ - 文档/规范中的哪个位置描述了如何在文本模式下将 '\n' 转换为特定于平台的行结尾?

javascript - 如何在 Node.js 中读取非常大(> 1GB)的 tar.gz 文件?

java - 底层流返回零字节

c# - 防止对 FILESTREAM 进行写操作?