c++ifstream中的Getline导致不必要的行为

Getline in c++ ifstream causing unwanted behavoir?

本文关键字:不必要 中的 Getline c++ifstream      更新时间:2023-10-16

我觉得getline函数有问题,它给了我一个与字符有关的错误。

我得到的错误是:

错误1错误LNK2019:未解析的外部符号"public: void __thiscall ArrayStorage::read(class std::basic_ifstream<char,struct std::char_traits<char> > &)"(?read@ArrayStorage@@QAEXAAV$basic_ifstream@DU$char_traits@D@std@@@std@@@Z)在函数_main C:\Users\Lewis \SVN\project1\main.obj 中引用

任何想法都将不胜感激。如果有人能用这种类型的数组更有效地完成这项任务,我会接受任何建议。

等等未解析的外部符号"public: void __thiscall阵列存储::读取(class std::basic_ifstream<char,struct std::char_traits<char> > &)"诸如此类

这是一个链接器错误。这意味着缺少函数ArrayStorage::read的定义。为什么?因为代码定义了一个名为read的函数,而不是ArrayStorage::read。如果您定义ArrayStorage::read:,它应该会找到它

//Array cpp:
void ArrayStorage::read(ifstream& fin)
// ...

一旦你通过了这一点,这个程序可能就可以运行了。您可能会因为读取循环而发现错误。while (! fin.eof() )不会"当文件不在末尾时[运行]"。它在上一次读取操作未尝试读取超过末尾时运行。考虑一下在进行检查时肯定已经发生了什么:

while (! fin.eof() ) // in the last iteration the read didn't go beyond the end of the file
{                    // so one more iteration is ran
    getline (fin,line); // tries to read past the end, fails
    if (line == "") continue; // line is unchanged, so it could be a non-blank line from before
    myArray[arrayIndex]=line; // Saves that line in the array:
                              // even though no line was read
    arrayIndex++;
} // goes back to the start of the loop, and only now !fin.eof() fails
  // but it's too late, the damage has been done

你可能不希望这种情况发生。你想在阅读失败后立即停止阅读。很简单:只需将读数作为条件:

while (getline (fin,line)) // if reading a line fails, the loop is not entered
{                          // and so no extra line is added to the array

您没有为Array::read()函数提供定义。您正在声明一个名为read()但与Array类无关的新函数。编译器和链接器并不关心它是否在名为Array.cpp的文件中。

试试这个:

void Array::read(ifstream& fin)
{
    //...
}

如果我还记得的话,这个链接器错误有时可能是由于您的类或它的一个基具有未定义的其他虚拟函数。错误发生在名为的函数上,而不是实际缺少定义的虚拟函数上,因为MSVC编译器会等待,直到找到第一个具有已定义虚拟函数的CPP文件,以便将类的类头定义函数的定义粘贴到其中,而当找不到此类CPP文件时,它永远不会定义类头定义的函数。GCC在这方面的表现与MSVC不同;我相信GCC会将定义粘贴在它们使用的每个对象文件中,并在链接时丢弃额外的内容。MSVC只定义了一次,因此可能会意外地从未定义过它。它之所以不能"只知道"它"忘记"插入定义,是因为编译器可以在任何时候增量调用,一次只对一些文件调用,所以它没有全局性。