从回购中发出读取单个文件的问题

Issue reading in single files from a repo

我正在从存储库中读取文件,但在编译代码时遇到问题。我的 github 合作伙伴(使用 mac)的代码没有问题,但是当我克隆他的 repo 时,我遇到了这个问题。

背景资料: 我最近进入 Linux 世界并且是 运行 小学。不确定这里是否有问题,因为我的其他编码项目有效,但这是背景信息。

error: no matching function for call to ‘std::basic_ifstream<char>::open(std::__cxx11::string&)’
 infile.open(fullPath); // Open it up!


   In file included from AVL.cpp:6:0:
    /usr/include/c++/5/fstream:595:7: note: candidate: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
           open(const char* __s, ios_base::openmode __mode = ios_base::in)
           ^

/usr/include/c++/5/fstream:595:7: note:   no known conversion for argument 1 from ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘const char*’
Makefile:4: recipe for target 'main' failed
make: *** [main] Error 1

这是我的函数:

void AVL::parseFileInsert(string fullPath) {
    ifstream infile;
    infile.open(fullPath); // Open it up!
    std::string line;
    char c;
    string word = "";
    //int jerry = 0;
    while (getline(infile, line))
    {
        // Iterate through the string one letter at a time.
        for (int i = 0; i < line.length(); i++) {

            c = line.at(i); // Get a char from string
            tolower(c);        
            // if it's NOT within these bounds, then it's not a character
            if (! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) ) {

                //if word is NOT an empty string, insert word into bst
                if ( word != "" ) {
                    insert(word);
                    //jerry += 1;
                    //cout << jerry << endl;
                    //reset word string
                    word = "";
                }
            }
            else {
                word += string(1, c);
            }
         }
     }
};

不胜感激!

采用 const std::string & 参数的 std::basic_fstream::open 重载已在 C++11 中引入。如果代码使用一个编译器编译而不是另一个编译器,那么一个编译器支持 C++11 而另一个不支持是有道理的(要么是因为太旧,要么是因为没有在命令行上指定 C++ 标准) .

如果您无法切换到 C++11 编译器(或更改命令行以启用 C++11 支持),您可以简单地更改代码行

infile.open(fullPath); // Open it up!

infile.open(fullPath.c_str()); // Open it up!

这不会改变语义,但有一个例外:std::string 支持嵌入的 NUL 字符,而 c_str() 返回的 C-style 字符串不支持。我不知道允许在 file/directory 名称中嵌入 NUL 字符的文件系统,因此这种差异是理论上的。