首頁 >後端開發 >C++ >為什麼 `ifstream::open(std::string)` 在舊 C 版本中失敗?

為什麼 `ifstream::open(std::string)` 在舊 C 版本中失敗?

Susan Sarandon
Susan Sarandon原創
2024-12-10 03:17:10492瀏覽

Why Does `ifstream::open(std::string)` Fail in Older C   Versions?

沒有符合函數: ifstream::open(std::string)

在包含下列行的 C 程式碼中:

file.open(name);

常見錯誤是:

no matching function for call 'std::ifstream::open(std::string&)'

出現此問題是因為舊版的 C(C 11 之前)不支援使用 std::string 參數開啟檔案。 open() 函數需要字元陣列或 C 風格字串。

解決方案

要解決此錯誤,可以使用以下方法之一:

  • 使用c_str() 將std:: string 轉換為C 風格字串方法:
file.open(name.c_str());
  • 利用ifstream 類別的建構函數,如下所示:
std::ifstream file(name.c_str());

這種方法無需單獨建構和

此外,為了確保loadNumbersFromFile() 函數不會修改其參數,建議引用常數std::string 來傳遞:

std::vector<int> loadNumbersFromFile(const std::string& name)
{
    // ...
}

以上是為什麼 `ifstream::open(std::string)` 在舊 C 版本中失敗?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn