C++ 中 ifstream读取txt文件内容
原创
©著作权归作者所有:来自51CTO博客作者流楚丶格念的原创作品,请联系作者获取转载授权,否则将追究法律责任
头文件
#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();
}
示例代码
#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;
}