c++题目 编写一个TXT文件阅读器
答案:1 mip版
解决时间 2021-01-16 21:39
- 提问者网友:我微笑着泪滴
- 2021-01-16 18:31
设计一TXT文件阅读器, 可以一次一屏(20或22行)显示文件内容, 每次显示完一屏内容后, 提示使用者键入一控制字符以控制屏幕翻滚。如字符'n'显示下一屏, 字符'p'返回上一屏, 字符'q'结束阅读 是读取txt文件的就可以了
最佳答案
- 二级知识专家网友:獨守空城
- 2021-01-16 19:22
#include <iostream>
#include <fstream>
#include <string>
#include <vector>using namespace std;class TxtReader
{
private:
ifstream txtfile;
static const int linesize;
static const int rowsize;
vector<fstrem::streampos> screenpos;
public:
TxtReader(string name);
void LastScreen();
void NextScreen();
void ShowContent();
~TxtReader();
};const int TxtReader::linesize = 22; //一屏22行
const int TxtReader::rowsize = 70; //一行70个字符TxtReader::TxtReader(string name)
{
txtfile.open(name);
if(!txtfile)
{
cout << "Open file failed!" << endl;
return;
}
screenpos.push_back(txtfile.tellg());
ShowContent();
}TxtReader::~TxtReader()
{
txtfile.close();
}void TxtReader::ShowContent()
{
char tmp[rowsize+1];
int line = 0;
while((!txtfile.eof())&&(line!=linesize))
{
txtfile.getline(tmp, rowsize+1);
line += 1;
cout << tmp << endl;
}
}void TxtReader::NextScreen()
{
if(txtfile.eof())
return; screenpos.push_back(txtfile.tellg());
ShowContent();
}void TxtReader::LastScreen()
{
if(screenpos.size() == 1)
return; txtfile.seekg(screenpos.back());
screenpos.pop_back();
ShowContent();
}int main()
{
cout << "Input the file name to open:" << endl;
string filename;
cin >> filename;
TxtReader reader(filename); char control;
while(cin >> control)
{
if(control == 'n')
reader.NextScreen();
if(control == 'p')
reader.LastScreen(); if(control == 'q')
break;
}
}
#include <fstream>
#include <string>
#include <vector>using namespace std;class TxtReader
{
private:
ifstream txtfile;
static const int linesize;
static const int rowsize;
vector<fstrem::streampos> screenpos;
public:
TxtReader(string name);
void LastScreen();
void NextScreen();
void ShowContent();
~TxtReader();
};const int TxtReader::linesize = 22; //一屏22行
const int TxtReader::rowsize = 70; //一行70个字符TxtReader::TxtReader(string name)
{
txtfile.open(name);
if(!txtfile)
{
cout << "Open file failed!" << endl;
return;
}
screenpos.push_back(txtfile.tellg());
ShowContent();
}TxtReader::~TxtReader()
{
txtfile.close();
}void TxtReader::ShowContent()
{
char tmp[rowsize+1];
int line = 0;
while((!txtfile.eof())&&(line!=linesize))
{
txtfile.getline(tmp, rowsize+1);
line += 1;
cout << tmp << endl;
}
}void TxtReader::NextScreen()
{
if(txtfile.eof())
return; screenpos.push_back(txtfile.tellg());
ShowContent();
}void TxtReader::LastScreen()
{
if(screenpos.size() == 1)
return; txtfile.seekg(screenpos.back());
screenpos.pop_back();
ShowContent();
}int main()
{
cout << "Input the file name to open:" << endl;
string filename;
cin >> filename;
TxtReader reader(filename); char control;
while(cin >> control)
{
if(control == 'n')
reader.NextScreen();
if(control == 'p')
reader.LastScreen(); if(control == 'q')
break;
}
}
我要举报
如以上问答内容为低俗/色情/暴力/不良/侵权的信息,可以点下面链接进行举报,我们会做出相应处理,感谢你的支持!
点此我要举报以上问答信息
推荐资讯