练习8.4

发布时间 2023-07-15 08:37:34作者: yuzuki_n

编写函数,以读模式打开一个文件,将内容读到一个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