首页 > 解决方案 > 如何将文件名作为参数传入并正确打开?

问题描述

void openfile(const string &db_filename) {
    ifstream file;
    file.open("db_filename");
    if(file.is_open())
    {
        cout<<"true"<<endl;
    }
    else cout<<"false"<<endl;}

我在这里有这个简单的代码来检查文件是否打开。但是,每当我运行它时,我都会出错。这意味着该文件未打开。我不知道为什么,但我确定文件在同一个文件夹中并且文件名输入正确。这段代码有什么问题吗?

标签: c++

解决方案


您将字符串文字传递"db_filename"open()而不是传递您的db_filename字符串对象。只需删除引号:

file.open(db_filename);

如果您的 STL 版本不支持传递 a std::stringto open(),请改为调用字符串的c_str()方法:

file.open(db_filename.c_str());

推荐阅读