头文件
#include <iostream>
#include <fstream>
#include <cassert>
#include <string>
把txt文件放在当前目录下
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();
}
示例代码
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cd3d324e56889791a810081e8c516f7b.png)
#include<stdio.h>
#include <iostream>
#include <fstream>
#include <cassert>
#include <string>
using namespace std;
void readTxt(string file)
{
ifstream infile;
infile.open("data.txt");
assert(infile.is_open());
string s;
while (getline(infile, s))
{
cout << s << endl;
}
infile.close();
}
void readTxt2(string file)
{
ifstream infile;
infile.open(file.data());
assert(infile.is_open());
char c;
while (!infile.eof())
{
infile >> c;
cout << c << endl;
}
infile.close();
}
void readTxt3(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();
}
int main()
{
readTxt("data.txt");
readTxt2("data.txt");
readTxt3("data.txt");
return 0;
}