天天看点

c++ primer 习题8.9/8.10

Exercise

8.9:

编写函数打开文件用于输入,将文件内容读入 string 类

型的 vector 容器,每一行存储为该容器对象的一个元

素。

Exercise

8.10:

重写上面的程序,把文件中的每个单词存储为容器的一个

元素。

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <stdlib.h>
using namespace std;

int main()
{
    //在文件text写入内容
    ofstream file("text.txt");
    file << "an apple\ntwo apple\nnone\nthis is an apple\n";
    file.close();

    //读文件到容器
    ifstream f;
    f.open("text.txt");
    vector<string> str;
    string s;
    if(!f)
    {
        cout << "open fail" <<endl;
        return ;
    }
    while(getline(f,s),!f.eof())//如果要读取单词则使用 (f >> s)
    {
        str.push_back(s);
    }
    //f.clear(); 如果要用该流重读多个文件则使用clear清除流
    f.close();

    //输出
    vector<string>::iterator iter = str.begin();
    while(iter != str.end())
    {
        cout << *iter <<endl;
        ++iter;
    }

    system("pause");
    return ;
}
           

继续阅读