簡體   English   中英

Getline在c ++ ifstream引起不必要的行為?

[英]Getline in c++ ifstream causing unwanted behavoir?

我想我的getline函數有問題,給我一個與charcters有關的錯誤。

我得到的錯誤是:

錯誤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中引用

任何想法將不勝感激。 如果有人使用這種類型的數組更有效地完成這項任務,我會接受任何建議。

blah blah blah unresolved外部符號"public: void __thiscall :: read (class std::basic_ifstream<char,struct std::char_traits<char> > &)" blah blah blah

這是鏈接器錯誤。 這意味着缺少函數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文件時,它永遠不會定義類頭定義的函數。 在這方面,海灣合作委員會的行為與MSVC不同; 我相信GCC會將定義粘貼在他們使用的每個目標文件中,並在鏈接時丟棄額外的內容。 MSVC只定義了一次,因此無意中定義它。 它不能“只知道”它“忘記”插入定義的原因是因為編譯器可以隨時以增量方式調用,一次只能調用某些文件,因此它沒有大圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM