這個字符串編輯程序是用單鏈表做的,程序最后要求輸出編輯后的字符串,比如執行替換操作,把o換成e,則原字符串Thisisabook.變為Thisisabeek.但是現在我寫的這個程序輸出的是Thisisabeek.單詞中間沒有空格。怎樣才能把空格加上呢?#include<iostream.h#include<malloc.htypedefstructnode{chardata;structnode*next;}node,*Lstring;//結構體定義voidcreat(Lstring&s){node*p1,*p2;s=(Lstring)malloc(sizeof(node));//新建頭結點cout<<"請輸入字符串:";p2=s;p1=p2;while(p1-data!='.')//建立鏈表{p1=(Lstring)malloc(sizeof(node));//新建首元結點cinp1-data;p2-next=p1;p2=p2-next;}p1-next=NULL;}voidinsert(Lstring&s)//插入函數{node*p1,*p2,*q;charc,x;repeat:;cout<<"需要在哪個字符之前插入?";cinc;for(p1=s,p2=p1;p1-next!=NULL;p1=p1-next)if(p1-next-data==c)p2=p1;if(p2==s){cout<<endl<<"字符串中不存在字符"<<c<<",請重新輸入!"<<endl<<endl;gotorepeat;}cout<<"請輸入欲插入的字符:";cinx;q=(Lstring)malloc(sizeof(node));q-data=x;q-next=p2-next;p2-next=q;}voiddel(Lstring&s){node*p,*q;charc;repeat:;cout<<"請輸入欲刪除的字符:";cinc;p=s;while(p-next-data!=c){p=p-next;if(p-next==NULL){cout<<endl<<"字符串中不存在字符"<<c<<",請重新輸入!"<<endl<<endl;gotorepeat;}}q=p-next;p-next=q-next;free(q);}voidtrans(Lstring&s){node*p;chara1,a2;inti=0;cout<<"請輸入被替換字符:";cina1;cout<<"請輸入替換的字符:";cina2;p=s;while(p-next!=NULL){if(p-next-data==a1){p-next-data=a2;++i;}p=p-next;}if(i==0){cout<<endl<<"字符串中不存在字符"<<a1<<",請重新輸入!"<<endl<<endl;trans(s);}}voidmain(){repeat2:;structnode*p;Lstringa;creat(a);cout<<endl<<"您可以輸入這3個指令之一:I—插入D—刪除R—替換"<<endl;repeat1:;cout<<endl<<"請輸入指令:";chary;ciny;if(y!='I'&&y!='D'&&y!='R'){cout<<endl<<"您輸入了一個錯誤指令,請重新輸入!"<<endl;gotorepeat1;}switch(y){case'I':insert(a);break;case'D':del(a);break;case'R':trans(a);break; }cout<<endl<<"結果是:";p=a-next;if(p==NULL)cout<<"空串"<<endl;else{while(p!=NULL){cout<data;p=p-next;}}rep:;cout<<endl<<endl<<"是否繼續編輯當前字符串?(y/n)";ciny;if(y=='y')gotorepeat1;elseif(y=='n')cout<<endl<<"是否重新輸入字符串?(y/n)";else{cout<<endl<<"請按Y或N進行選擇!";gotorep;}ciny;if(y=='y'){cout<<endl<<endl;gotorepeat2;}}

熱心網友

源碼錯誤不少。略一看,發現問題,(不包括風格的問題)在創建鏈表時,輸入字符cin的方法不對。會過濾空格,作為下一次輸入的標志。可以查一下,創建之后輸出來應該也沒有空格符。while(p1-data!='.') //建立鏈表{p1=(Lstring)malloc(sizeof(node)); //新建首元結點cinp1-data;}