文章搜索——初步完成之前的构想
今天,完成了王老师交代的作业1的任务,用了C++语言编写,开始只是想了个基本的框架,开始读文件用了STRING类型,数据处理用了结构体指针。在编写过程中也遇到了种种困难,但都解决了。
#include<fstream> #include<iostream> #include<string> using namespace std; typedef struct words{ string word; int num; struct words *next; }words,*Linklist; int InitList_L(Linklist &L) { L=new words; L->next=NULL; return 1; } void Paixu(Linklist L) { cout.width(10); cout<<"单词"<<" "<<"次数"<<endl; string s; int temp; Linklist p,p1; p1=L->next; for(int i=0;i<10;i++){ p=p1->next; while(p) { if(p->num>p1->num) { temp=p1->num; p1->num=p->num; p->num=temp; s=p1->word; p1->word=p->word; p->word=s; } p=p->next;} cout.width(10); cout<<p1->word<<" "<<p1->num<<endl; p1=p1->next; } } int main() { cout<<"请输入文件的名称:"<<endl; char filename[30]; cin>>filename; Linklist L; InitList_L(L); string w; ifstream fin; fin.open(filename,ios::in); if(!fin) {cout<<"打开错误!"<<endl; return 0;} Linklist p,s,q; while(fin>>w) { int a=0; q=L; p=L->next; while(p){ if(p->word==w) {p->num+=1; a++;} p=p->next; q=q->next;} if(a==0) { s=new words; s->word=w; s->num=1; q->next=s; s->next=NULL;} } Paixu(L); return 0; }
其实在C++语言下管理文件输入包含两步,将流与输入去向的程序管理起来,另外就是将流与文件连接起来,我还学会了方法字段宽度的设置方法,解决了文件输出对齐的问题。