【问题标题】:Issue reading in single files from a repo从回购中读取单个文件的问题
【发布时间】:2018-03-07 08:18:02
【问题描述】:

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

背景信息: 我最近进入 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);
            }
         }
     }
};

非常感谢!

【问题讨论】:

  • 显而易见的尝试是infile.open(fullPath.c_str()); // Open it up!,但您似乎使用的是 c++11,并且从 c++11 开始可以使用 std::string 作为文件名打开文件,所以我不确定。
  • infile.open(fullPath); 返回什么?
  • @user:未编译的代码将无法运行。不运行的代码不会返回任何东西。
  • @john 是的,那是我尝试过的原始方法之一,但无济于事。还有其他想法吗?

标签: c++ visual-studio fstream


【解决方案1】:

在 C++11 中引入了采用 const std::string &amp; 参数的 std::basic_fstream::open 重载。如果代码用一个编译器编译而不是另一个编译器,那么一个编译器支持 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 字符的文件系统,因此这种差异是理论上的。

【讨论】:

  • 谢谢,我因为没有 c_str 的“()”而搞砸了。感谢您清除它!
猜你喜欢
  • 1970-01-01
  • 2011-09-28
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
相关资源
最近更新 更多