从存储库读取单个文件时出现问题

Issue reading in single files from a repo

本文关键字:问题 文件 单个 存储 读取      更新时间:2023-10-16

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

背景信息:我最近进入了Linux世界,正在运行Elementary。不确定这里是否存在问题,因为我的其他编码项目有效,但这是背景信息。

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);
            }
         }
     }
};

任何事情都非常感谢!

std::basic_fstream::open overload采用const std::string &参数已在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 样式字符串不支持。我不知道允许在文件/目录名称中嵌入 NUL 字符的文件系统,因此这种差异是理论上的。