温馨提示×

ifstream如何一行一行读取

小樊
82
2024-06-26 14:21:44
栏目: 编程语言

要一行一行读取一个文件,可以使用std::getline()函数来实现。下面是一个简单的示例代码,演示了如何使用std::getline()函数逐行读取文件内容:

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

int main() {
    std::ifstream file("example.txt");
    std::string line;

    if (file.is_open()) {
        while (std::getline(file, line)) {
            std::cout << line << std::endl;
        }
        file.close();
    } else {
        std::cout << "Failed to open the file." << std::endl;
    }

    return 0;
}

在这个示例中,程序首先尝试打开名为example.txt的文件。然后,使用std::getline()函数逐行读取文件内容并输出到控制台。最后,关闭文件流。如果文件无法打开,程序会输出一条错误消息。

确保将example.txt替换为您要读取的实际文件名。

0