实验结论
Part1:验证性实验
运行结果截图:
Part2:基础练习
源代码:
#include
#include
using namespace std;
int main() {
ofstream fs("3.txt", ios_base::app | ios_base::binary);
fs << "\nmerge successfully.";
fs.close();
return 0;
}
运行结果:
Part3:应用编程实践
1.点名程序
源代码(只包含主程序):
#include
#include
#include
#include
#include
#include
#include "utils.h"
using namespace std;
int main() {
srand(time(NULL));
int n;
string rfilename,wfilename;
cout << "输入名单列表文件名:";
cin >> rfilename;
cout << "输入随机抽点人数:";
cin >> n;
ifstream ifs(rfilename);
wfilename = getCurrentDate()+".txt";
ofstream ofs(wfilename);
vector
lineStartPosi.push_back(ifs.tellg());
while (ifs) {
char tmpc;
ifs.read(&tmpc, sizeof(tmpc));
if (tmpc == '\n')
lineStartPosi.push_back(ifs.tellg());
}
ifs.clear();
int maxN = lineStartPosi.size();
int* mark = new int[maxN]; //维护一个标记数组,以确保随机抽取的名单中不会出现重复信息
for (int i = 0; i < maxN; i++)
mark[i] = 0;
while (n) {
int idx = rand() % maxN;
if (mark[idx] == 1)
continue;
ifs.seekg(lineStartPosi[idx]);
string str;
getline(ifs, str);
cout << str << endl;
ofs << str << endl;
mark[idx] = 1;
n--;
}
return 0;
}
运行结果:
文件内容:
2.字符数统计
源代码:
#include
#include
#include
#include
using namespace std;
int main() {
string filename;
int numOfChar = 0, numOfWord=0, numOfLine=0;
cout << "输入要统计的英文文本文件名:";
cin >> filename;
ifstream fs(filename);
char ch;
while ((ch = fs.get()) != EOF)
if(ch!='\n')
numOfChar++;
fs.clear();
fs.seekg(ios::beg);
string str;
while (fs >> str)
numOfWord++;
fs.clear();
fs.seekg(ios::beg);
while (getline(fs, str))
numOfLine++;
cout << "字符数:" << numOfChar << endl;
cout << "单词数:" << numOfWord << endl;
cout << "行数:" << numOfLine << endl;
return 0;
}
待统计文本:
统计结果:
实验总结与体会
在part3的程序一中,第28行ifs.clear()是必要的。对于seekg()函数,C++参考手册中提到“If the eofbit flag is set before the call, the function fails (sets failbit and returns).”,所以在使用前需要重设输入流中的内部指针,当然,也可以简单地通过将文件关闭后再重新打开来解决这一问题……但是,为了保持我一贯准确节制凝练清晰的优秀代码风格,一行就能解决的问题怎么能用两行!﹁_﹁
……话是这么说,但实际上更多的还是基于语义上的考虑,如果我只是想重设内部指针状态的话,把文件关闭再打开就显得不够自然了