c++ifstream中的Getline导致不必要的行为
Getline in c++ ifstream causing unwanted behavoir?
我觉得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只定义了一次,因此可能会意外地从未定义过它。它之所以不能"只知道"它"忘记"插入定义,是因为编译器可以在任何时候增量调用,一次只对一些文件调用,所以它没有全局性。
- 不必要的C++代码最终会出现在我完成的程序中吗?
- 合并文本文件不同行中的重复项
- 在 c++ 中不必要的包含
- 在序列化过程中删除不必要的内存分配
- 在C++/虚幻引擎4中访问不同类中的静态变量
- 分配不同类中的对象的值
- 获取带有字符串的变量,而不C++中的 if-else
- C++-从不同的类中获取不同类中的变量集
- 将不同组中的C++文件包含在目标C++测试中
- 处理对“vector_binary_operation”类中“表达式”的引用,而无需不必要的副本
- Eclipse CDT 中不必要的导入
- 不必要的 std::在 cpp 首选项示例中result_of向前使用
- 不同类中的枚举访问
- 如何在c++中访问定义在不同类中的变量
- 获取访问不同类中的顶级变量和方法
- 访问不同类中的成员
- 如何在不使用任何不必要空间的情况下合并三个排序数组
- 使用不同类中的类对象获取不正确的数据
- 不同类中的多个j2me commandAction方法没有响应
- 无法使用 "Friend" 到达不同类中的向量