首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

C++从txt文件中读取getline并存储到字符串数组中

C++从txt文件中读取getline并存储到字符串数组中的方法如下:

代码语言:txt
复制
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main() {
    std::ifstream file("example.txt"); // 打开txt文件
    std::vector<std::string> lines; // 创建字符串数组

    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) { // 逐行读取文件内容
            lines.push_back(line); // 将每行内容存储到字符串数组中
        }
        file.close(); // 关闭文件
    } else {
        std::cout << "无法打开文件" << std::endl;
        return 1;
    }

    // 打印存储的字符串数组内容
    for (const auto& line : lines) {
        std::cout << line << std::endl;
    }

    return 0;
}

上述代码首先使用std::ifstream打开名为"example.txt"的txt文件。然后,创建一个std::vector<std::string>类型的字符串数组lines来存储文件中的每一行内容。

接下来,通过file.is_open()检查文件是否成功打开。如果成功打开,使用std::getline()逐行读取文件内容,并将每行内容存储到字符串数组lines中。

最后,使用一个循环遍历打印存储的字符串数组内容。

这是一个简单的示例,你可以根据实际需求进行修改和扩展。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券