练习8.4

编写函数,以读模式打开一个文件,将内容读到一个vector《string》里面,将每一行为一个元素存到vector里面

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

int main()
{
    std::vector<std::string> content;
    std::ifstream is("test.txt");
    std::string line;
    while (std::getline(is, line))
    {
        content.push_back(line);
    }

    for (auto line : content)
    {   
        std::cout << line << std::endl;
    }
}
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    ifstream in("main.cpp");
    if (!in)
    {
        cerr << "无法打开输入文件" << endl;
        return -1;
    }

    string line;
    vector<string> words;
    while (getline(in, line))
    {
        words.push_back(line);
    }
    in.close();

    for (auto& word : words)
    {
        cout << word << endl;
    }

    return 0;
}

书上的代码,我觉得主要是比我多了,判断读文件是否成功了,读完之后记得close

posted @   yuzuki_n  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示