您的位置:首页 > 编程语言 > C语言/C++

8.9 编写函数打开文件用于输入,将文件内容读入 string 类型的 vector 容器,每一行存储为该容器对象 的一个元素。8.10 重写上面的程序,把文件中的每个单词存储为 容器的一个元素

2016-03-04 13:11 726 查看
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;

//8.9
//8.10
int main()
{
vector<string> files;
string fileName = "fileList.txt";
fstream f; //可读写
f.open(fileName);

if(!f) //打开失败
{
cout <<"Sorry! open file failed!" << endl;
return 0;
}

char name[1024]; //
while(cin.get(name,1024,'\n'),!cin.eof()) //输入
{
f << name << '\n'; //输入到文件
fflush(stdin); //清除流里面的回车
}

f.clear(); //清除流
f.close(); //关闭文件 这样写入的文件才能生效 一遍后面读到vector

f.open(fileName); //再次打开来读
char chs[1024];

while(f.getline(chs,1024))
{
//cout << chs << endl;
files.push_back(chs);
}
f.clear();
f.close();
for(vector<string>::iterator iter = files.begin(); iter < files.end(); iter ++) //遍历vector 容器
{
cout << *iter;

}
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++