1.


#include<iostream> #include<fstream> #include<string> #include<cstdlib> using namespace std; int main(){ string filename; cout << "输入打开的文件: "; cin >> filename; ofstream fout; fout.open(filename,ios_base::app); if(!fout.is_open()){ cerr << "fail to open " << filename << endl; system("pause"); exit(0); } fout << endl << "merge successfully" << endl; return 0; }
运行结果如下:
2.代码如下:


#include <iostream> #include <string> #include "utils.h" #include <fstream> #include <cstdlib> #include <time.h> using namespace std; int main() { string filename,listfilename,name; filename = getCurrentDate(); cout << filename << endl; int n,num[100],luckydog,i=1,j; cout << "输入名单列表文件名:"; cin >> listfilename; cout << "输入随机抽点人数: " ; cin >> n; ifstream fin; ofstream fout; fin.open(listfilename); if(!fin.is_open()){ cerr << "fail to open " << listfilename << endl; system("pause"); exit(0); } fout.open(filename,ios_base::app); if(!fout.is_open()){ cerr << "fail to open " << filename << endl; system("pause"); exit(0); } srand(time(0)); while(n--){ luckydog=1+rand()%83; num[i]=luckydog; i++; fin.clear(); fin.seekg(0); for(j=1;j<=luckydog;j++) getline(fin,name); fout << name << endl; cout << name << endl; } fout << endl; fin.close(); fout.close(); return 0; }
(就上传了main函数的部分)
运行结果:
3.代码如下:


#include<iostream> #include<cstdlib> #include<string> #include<fstream> using namespace std; int main(){ string filename; cout << "输入要统计的英文文本文件名:"; cin>>filename; ifstream fin; fin.open(filename); if(!fin.is_open()){ cerr << "fail to open " << filename << endl; system("pause"); exit(0); } int num_ch=0,num_word=0,num_line=0; char ch; int flag=1; while(fin.get(ch)){ if(ch==' '){ num_ch++; if(flag==0)//如果有空格就能统计后面的单词 flag=1; } else if(ch=='\n'){//换行时统计行数 num_line++; if(flag==0) flag=1; } else if(flag&&((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))){ //统计单词数以及单词的第一个字符 flag=0; num_ch++; num_word++; } else num_ch++; //单词剩下的字符数 } if(ch!='\n')//如果最后一个字符不是换行,行数加一 num_line++; cout << "字符数:" << num_ch << endl; cout << "单词数: " << num_word << endl; cout << "行数: " << num_line << endl; fin.close(); return 0; }
运行结果如下:
1.我第二题随机函数一开始是所有的人名字都一样。然后我把srand(time(0))放在main函数外面,就可以了。但是我main函数里面没有讨论如果相同的情况。
2.统计单词数要注意的是行数,因为它最后一行可能没有'\n',一定要注意,不然的话,行数就是2。
3.一开始写还会出现fail to open的情况就是因为我那个项目没有和list.txt放在一起。