温馨提示×

c++怎么从文件中读取字符串

c++
小亿
113
2023-12-07 20:21:44
栏目: 编程语言

在C++中,可以使用std::ifstream类从文件中读取字符串。以下是一个示例代码:

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

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

    if (file.is_open()) { // 检查文件是否成功打开
        std::string str;

        while (std::getline(file, str)) { // 逐行读取文件内容
            std::cout << str << std::endl; // 打印读取的字符串
        }

        file.close(); // 关闭文件
    } else {
        std::cout << "无法打开文件" << std::endl;
    }

    return 0;
}

在上述代码中,使用std::ifstream类打开文件,并使用std::getline函数逐行读取文件内容到字符串str中。然后,通过std::cout打印读取的字符串。最后,使用file.close()关闭文件。

注意:在使用std::ifstream时,需要包含<fstream>头文件;在使用std::string时,需要包含<string>头文件。此外,确保文件名和路径正确,并且文件存在于指定的位置。

0