1.读数据的头文件
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
2.读数据的流程
创建输入流对象ifstream
利用输入流对象打开文件,参数为文件路径和打开模式ios::in
判断是否可以打开文件,如果打开文件失败,终止程序,否则继续
从输入流对象按行读取数据,并存放起来
读取数据完毕,关闭文件。
3. 读数据的三种方式
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(void)
{
string filepath = "C:\\Users\\10307\\Desktop\\text\\test.txt";
ifstream fin;
fin.open(filepath, ios::in);
if (fin.is_open() == false)
{
cout << "打开文件" << filepath << "失败。\n";
return 0;
}
string buffer;
cout << "读取文件的第二种方式" << endl;
char buffer1[101];
while (fin.getline(buffer1, 100))
{
cout << buffer1 << endl;
}
cout << "读取文件的第三种方式" << endl;
string buffer3;
while (fin >> buffer3)
{
cout << buffer3 << endl;
}
fin.close();
return 0;
}