读写文件需要用到fstream类,详述可查阅《C++ Primer》第八章。
下面给出例子:
【读取文件内容】
【代码】
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int main(int argc, char**argv)
{
fstream myfile;
myfile.open("./test.txt", ifstream::in);
if (myfile.is_open())
{
//方法一:使用getline,一行一行地读
vector<string> vStr;
string buff;
while (getline(myfile, buff))
{
vStr.push_back(buff);
}
//注意:使用以下两种方法,遇到空格,会自动换行
//方法二:使用流
//string buff;
//vector<string> vStr;
//while (myfile >> buff)
//{
// vStr.push_back(buff);
//}
//方法三:使用istream_iterator迭代器
//vector<string> vStr;
//istream_iterator<string> in(myfile), end;
//while (in != end)
//{
// vStr.push_back(*in++);
//}
//方法三可以简写为:
//istream_iterator<string> in(myfile), end;
//vector<string> vStr(in, end);
//打印读取到的内容
for(auto i : vStr)
{
cout << i<< endl;
}
}
myfile.close();
system("pause");
}
【读取结果】
方法一:
方法二和方法三: