天天看點

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 ;
}
           

繼續閱讀