C++文件读(逐行读、逐单词读)

#include
#include
#include
#include
#include
using namespace std;

int main()
{
vector text;//创建vector对象
ifstream ifile;//创建输入文件流对象
ifile.open("Test.txt",ifstream::in);//打开文件
if(!ifile)//判断是否打开成功
cerr<<"open failed"<
//初始化vector对象
string line,word;
while(getline(ifile,line))//逐行读
{
istringstream istrm(line);//创建字符串流
while(istrm>>word)//逐单词读
text.push_back(word);
}
ifile.clear();
ifile.seekg(0);//文件重定位
while(ifile>>word) cout<
ifile.close();//关闭文件
vector::iterator it=text.begin();
while(it!=text.end())//遍历vector容器
{
cout<<*it++<
}
return 1;
}

注:
1.ifstream的对象可直接用于文件的逐单词读(ifstream的头文件为fstream)
2.getline函数可直接获取某一行
3.istringstream的对象可用于文本的逐单词读(istringstream的头文件为sstream)

你可能感兴趣的:(C/C++)