溫馨提示×

ifstream如何讀取文件內(nèi)容

小樊
293
2024-06-26 14:16:53
欄目: 編程語言

使用ifstream可以很方便地讀取文件內(nèi)容。以下是一個簡單的示例代碼,展示了如何使用ifstream讀取文件內(nèi)容:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("example.txt"); // 打開文件

    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) { // 逐行讀取文件內(nèi)容
            std::cout << line << std::endl;
        }

        file.close(); // 關(guān)閉文件
    } else {
        std::cout << "無法打開文件" << std::endl;
    }

    return 0;
}

在上面的示例中,我們首先創(chuàng)建了一個ifstream對象file,并指定要打開的文件名為example.txt。然后,我們使用std::getline函數(shù)逐行讀取文件內(nèi)容,并將每行內(nèi)容輸出到控制臺。最后,我們關(guān)閉文件。

請確保文件存在且路徑正確,否則將無法成功打開文件。

0