★☆題目4(無憂id 24題 上機(jī)題庫id 9 字符串單詞倒置題)
函數(shù)readdat()實(shí)現(xiàn)從文件in.dat中讀取一篇英文文章存入到字符串?dāng)?shù)組中,請編制函數(shù)strol(),其函數(shù)的功能是:以行為單位對行中以空格或標(biāo)點(diǎn)符號為分隔的所有單詞進(jìn)行倒排。最后把已處理的字符串(應(yīng)不含標(biāo)點(diǎn)符號)仍按行重新存入字符串?dāng)?shù)組中,最后調(diào)用函數(shù)writedat()把結(jié)果輸出到文件out6.dat中。
例如:原文:you he me
i am a student.
結(jié)果:me he you
student a am i
原始數(shù)據(jù)文件存放的格式是:每行的寬度均小于80個字符,含標(biāo)點(diǎn)符號和空格。
部分源程序存在文件prog1.c中。
請勿改動主函數(shù)main()、讀數(shù)據(jù)函數(shù)readdat()和輸出數(shù)據(jù)函數(shù)writedat()的內(nèi)容。
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
char [50][80];
int maxline=0;/*文章的總行數(shù)*/
int readdat(void);
void writedat(void);
/*在無憂及上機(jī)題庫版模擬系統(tǒng)中都通過測試(輸入文件句末有標(biāo)點(diǎn)的在輸出文件中句前有空格*/
void strol(void)
{ int i,j,k,s,m,strl;
char str[80];
for(i=0;i<maxline;i++)
{ strl=strlen([i]);
memset(str,0,80); /*初始化這字符串?dāng)?shù)組str*/
s=k=0;
for(j=strl-1;j>=0;j--) /*從當(dāng)前字符串尾部開始向前倒序循環(huán),實(shí)現(xiàn)題意要求的倒排*/
{ if(isalpha([i][j])) k++; /*如果當(dāng)前字符是字母a~z或a~z,則k加一*/
else { for(m=1;m<=k;m++) /*否則將長度為k的單詞順序存入到字符串?dāng)?shù)組str中,s值加1*/
str[s++]=[i][j+m];
k=0; /*將k值清0,以方便下一個單詞的長度計數(shù)*/
}
if(!isalpha([i][j])) str[s++]=' '; /*如果當(dāng)前字符不是字母a~z或a~z,則以空格代之存入到字符串?dāng)?shù)組str中,s值加一*/
}
for(m=1;m<=k;m++) /*此時的k值為當(dāng)前字符串中第一個單詞的長度,但在上一個for循環(huán)中沒能存入到字符串?dāng)?shù)組str中,所以在這里將其存入到str中*/
str[s++]=[i][j+m];
str[s]='\0'; /*在當(dāng)前行尾加0以標(biāo)記此行的結(jié)束*/
strcpy([i],str); /*將倒排好的當(dāng)前字符串重新存回到當(dāng)前行中*/
}
}
void main()
{
clrscr();
if(readdat()){
printf("數(shù)據(jù)文件in.dat不能打開!\n\007");
return;
}
strol();
writedat();
}
int readdat(void)
{
file *fp;
int i=0;
char *p;
if((fp=fopen("in.dat","r"))==null) return 1;
while(fgets([i],80,fp)!=null){
p=strchr([i],'\n');
if(p)*p=0;
i++;
}
maxline=i;
fclose(fp);
return 0;
}
void writedat(void)
{
file *fp;
int i;
clrscr();
fp=fopen("out6.dat","w");
for(i=0;i<maxline;i++){
printf("%s\n",[i]);
fprintf(fp,"%s\n",[i]);
}
fclose(fp);
}