本文转自:https://www.cnblogs.com/nkzhangcheng/p/7722568.html
首先添加头文件:
#include <iostream>
#include <fstream>
#include <cassert>
#include <string>
1. 逐行读入
void readTxt(string file)
{
ifstream infile;
infile.open(file.data()); //将文件流对象与文件连接起来
assert(infile.is_open()); //若失败,则输出错误消息,并终止程序运行
string s;
while(getline(infile,s))
{
cout<<s<<endl;
}
infile.close(); //关闭文件输入流
}
2. 逐个字符读入(忽略空格与回车)
void readTxt(string file)
{
ifstream infile;
infile.open(file.data()); //将文件流对象与文件连接起来
assert(infile.is_open()); //若失败,则输出错误消息,并终止程序运行
char c;
while (!infile.eof())
{
infile >> c;
cout<<c<<endl;
}
infile.close(); //关闭文件输入流
}
3. 逐个字符读入(包括空格与回车)
void readTxt(string file)
{
ifstream infile;
infile.open(file.data()); //将文件流对象与文件连接起来
assert(infile.is_open()); //若失败,则输出错误消息,并终止程序运行
char c;
infile >> noskipws;
while (!infile.eof())
{
infile>>c;
cout<<c<<endl;
}
infile.close(); //关闭文件输入流
}