c++ - 尝试将字符串变量与 infile.open() 一起使用在 C++ 中被视为 char

标签 c++ string c++11 getline

我正在尝试制作一个程序,用户可以在其中输入文件名,然后该程序会尝试打开它并检查它是否已打开。我正在使用 getline 函数。到目前为止,这是我的代码:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;


void readGameFile();

int main()
{
    readGameFile();
    return 0;
}


void readGameFile()
{
    ifstream infile;
    string s;
    string fileName;
    getline(cin,fileName);
    infile.open(fileName);
    if(infile.is_open())
    {
        cout << "It worked!"<<endl;
    }
    else
    {
        cout << "You messed up"<<endl;  
    }
}

它给我这个错误: 23:22:错误:没有匹配函数来调用“std::basic_ifstream::open(std::string&)”

23:22:注意:候选人是: /usr/include/c++/4.6/fstream:531:7: 注意:void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits, std::ios_base::openmode = std::_Ios_Openmode] /usr/include/c++/4.6/fstream:531:7: 注意:参数 1 没有从‘std::string {aka std::basic_string}’到‘const char*’的已知转换

所以,我不太确定问题出在哪里。我对编程还很陌生,我正在尝试为一个类(class)项目解决这个问题(这不是作业,它只是我目前在我的项目中遇到的问题的通用版本)。如果你能提供任何帮助,那就太好了。谢谢!

最佳答案

open 有两个重载:

void open( const char *filename, ios_base::openmode mode = ios_base::in );
void open( const std::string &filename, ios_base::openmode mode = ios_base::in );

第二个仅在 C++11 之后可用。您显然不是在 C++11 模式下编译,就是使用过时的编译器。还有另一个重载需要 const char*,所以无论如何这都应该工作:

infile.open(fileName.c_str());

关于c++ - 尝试将字符串变量与 infile.open() 一起使用在 C++ 中被视为 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29725759/

相关文章:

c++ - 免费谷歌翻译

c++ - 程序流程并以安全和 Eloquent 方式正确地将控制权返回给 main()

c++ - 确定空无限循环的编译器行为的最佳方法是什么?

iphone - 如何将字符串拆分成句子 cocoa

c++ - std::ostringstream 覆盖初始化字符串

c++ - 智能指针是否排除了两阶段 build 的需要?

c++ - 访问嵌套类(表现得像 friend ,但又不是)

Java 内置方法 - 字符串中字符的出现次数

c - 给定起始和结束索引,如何在 C 中复制字符串的一部分?

c++ - to_string 不是 std 的成员,g++ (mingw)