1,读取文件的类为ifstream,其中“i”代表“in”,针对变量而言,ifstream所在的头文件为fstream;
2,ifstream中有open方法,可以打开文件;
3,ifstream中有>>方法,可以以空格为分割符,以换行为结束符读取数据;
4,iostream中有getline(ifst, strline)方法,可以读取每一行的字符串数据。
以空格为分割符读取数据的代码如下:
/*
* 从文件中读取数据,默认以“ ”作为一个单元,无论是int还是string。
* */
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
//读操作
ifstream istr;
string temp;
vector<string> veci;
istr.open("test.txt");
//以换行符作为结束
while (istr >> temp )
{
veci.push_back(temp );
}
for(auto ite = veci.begin(); ite < veci.end(); ++ite)
{
cout << "*" << *ite << endl;
}
istr.close();
}
读取每一行数据的代码如下:
/*
* 从文件中读取每一行数据。
* */
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
//读操作
ifstream istr;
string temp;
vector<string> veci;
istr.open("test.txt");
string strline;
while(getline(istr, strline))
{
cout << strline << endl;
}
istr.close();
}