实验6
1.验证性实验:合并txt文件


2.3.txt末尾追加内容。
#include<iostream> #include<string> #include<fstream> using namespace std; int main(){ ofstream ofapp("3.txt",ios::app); string add; if(!ofapp){cerr<<"open error"<<endl;} getline(cin,add); ofapp<<add<<endl; ofapp.close(); system("pause"); return 0; }

3.随机抽取并创建txt文件
#include<iostream> #include<fstream> #include<string> #include<ctime> #include<cstdlib> #include "utils.h" using namespace std; int main(){ int i=0,j,n; int result,mo; fstream fread0("list.txt"); string name[100]; string line; while(getline(fread0,line)){ name[i]=line; i++; } cin>>n; srand(time(NULL)); int a[100]; for(j=0;j<n;j++) { while(1){ result=rand()%i; mo=1; for(int k=0;k<j;k++) { if(result==a[k]) mo=0; } if(mo==1) break; } a[j]=result; } string filename; filename = getCurrentDate()+".txt"; fstream fout(filename,ios::app); for (i = 0;i < n;i++) { fout << name[a[i]] << endl; } system("pause"); return 0; }

4.读取txt字符个数,单词个数,行数。
#include<iostream> #include<fstream> #include<string> using namespace std; int main() { string filename; cout << "输入要统计的英文文本文件名:"; cin >> filename; char a[1000]; int i = 0, sn = 0, ln = 1, cn = 0; fstream readchar(filename); while (readchar.get(a[i])) { if ((a[i] == ' ' || a[i] == '\n' || a[i] == '.' || a[i] == '\t' || a[i] == ',') && (a[i - 1] != ' ' && a[i - 1] != '\n' && a[i - 1] != '.' && a[i - 1] != '\t'&&a[i - 1] != ',')) sn++; if (a[i] == '\n') ln++; if (a[i] != '\n') cn++; i++; } cout << "字符数:" << cn << endl << "单词数:" << sn << endl << "行数:" << ln << endl; readchar.close(); system("pause"); return 0; }

总结反思
1文件要记得close,上面好像有一个我没有close。
2文件fstream可以用来读写,但不知道和ifstream以及ofstream有什么区别。
浙公网安备 33010602011771号