手动输入文件名的ifstream

4
我可以在终端中手动输入文件名吗?
例如,程序会询问我要打开哪个文件。我会手动输入“test.txt”,然后它就会打开 test.txt。 但是,我的编译器会发出以下错误:
no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::string&)'

我的代码:

int main() {
    string input;
    cout << "Please enter the name of the file\n";
    cout << "Input: ";
    getline (cin, input);

    ifstream file (input);

    if (file.is_open()) {
        // blah
    } else {
        // blah
    }
}

我该如何手动输入文本文件名?

@JonnyHenly 好的,它的意思是:没有找到与 'std::basic_ifstream<char>::basic_ifstream(std::string&)' 匹配的函数 - Jake D
你是否包含了 ifstream 的正确头文件?应该使用 include <fstream> 进行包含。 - Jonny Henly
@JonnyHenly #include <fstream>?如果是的话,是的,我已经包含了它。 - Jake D
@JerryCoffin 哦。那个起作用了!这是怎么回事.. - Jake D
1
@JerryCoffin,我如何为您回答我的问题打分呢? - Jake D
1个回答

1
如果您使用的是旧版(C++11之前)编译器,则必须使用:
ifstream file (input.c_str());

虽然文件名类似于字符串,C++98 有 std::string,但它们没有将两者结合起来(可以这么说),因此在 C++98 中,指定要打开的文件名称的类似字符串必须被指定为 char const *(即 C 风格字符串),而不是 std::string。我预测,在仅支持 char const *std::string 作为名称时,这看起来(至少接近)同样愚蠢--一旦我们习惯使用范围,显然应该只是某些字符类似物的范围。

谢谢你的帮助!:D - Jake D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接