200分又是C语言问题
函数ReadDat()实现从文件IN.DAT中读取一篇英文文章存入到字符串数组xx中,请编制函数StrOL(),其函数的功能是:以行为单位对行中以空格或标点符号为分隔的所有单词进行倒排。最后把已处理的字符串(应不含标点符号)仍按行重新存入字符串数组xx中,最后调用函数writeDat()把结果xx输出到文件OUT6.DAT中。
例如:原文:You He Me
I am a student.
结果:Me He You
student a am I
原始数据文件存放的格式是:每行的宽度均小于80个字符,含标点符号和空格。
部分源程序存在文件prog1.c中。
请勿改动主函数main()、读数据函数ReadDat()和输出数据函数writeDat()的内容。
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
char xx[50][80];
int maxline=0;/*文章的总行数*/
int ReadDat(void);
void WriteDat(void);
void StrOL(void){这段为答案(1)
}
void main()
{
clrscr();
if(ReadDat()){
printf("数据文件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(xx[i],80,fp)!=NULL){
p=strchr(xx[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",xx[i]);
fprintf(fp,"%s\n",xx[i]);
}
fclose(fp);
}
答案(1)为{int I,j,k,strl,l;char c;
for(I=0;I<maxline;I++)
for(j=0;j<strlen(xx[I]);j++)
{c=xx[I][j];
if ((c>='A'&&c<='Z')||(c>='a'&&c<='z')||c==' ') ;
else xx[I][j]=' '; }
for(l=0;l<maxline;l++)
{char ch[80]={0}; char pp[80]={0};
strl=strlen(xx[l]);
I=strl-1; k=1;
while(1)
{while (((xx[l][I]>='a'&&xx[l][I]<='z')||(xx[l][I]>='A'&&xx[l][I]<='z'))&&I>=0)
{for(j=k;j>=0;j--)
pp[j+1]=pp[j]; pp[0]=xx[l][I]; k++;I--; }
strcat(ch,pp);strcpy(pp, """");k=1;
if(I==-1)break;
while((xx[l][I]<'A'||xx[l][I]>'z')&&I>=0)
{for(j=k;j>=0;j--)
pp[j+1]=pp[j]; pp[0]=xx[l][I]; k++; I--;}
strcat(ch,pp); strcpy(pp,"""");
k=0;
if(I==-1)break;}
strcpy(xx[l],ch);
}
}
我的提问是答案中的语句
第一个问题:第二个和第三个while 为什么换不成if!
第二问题为什么少了k++:
输出会变成an ren hae Yoa
ma a in arn
st wht
de Ece
ge ine win
wh wah ina
tur inu
po cao wia
en lin thi toh
a an prn Ecr
ca ena cln
co noo
a ma toa hao Yoa
tw thw beh che
le noe wro shr Yoh
Wr 25r th5
on arn yor
2 SH ANH
原来输出答案an read have You
magazine a in article
states which
development Economic
generate inevitably will
which waste industrial
turn in
pollution cause will
environment living the to
a and prosperity Economic
can environment clean
coexist not
a make to have You
two the between choice
less no write should You
Write 250words than
on article your
2 SHEET ANSWER
请各位高手指教!
参考答案:1.很简单,程序是一个一个字符的读取,需要每次都判断读取的是否是字母或是行首,用if一次判断就没了,不符合程序的算法,第一个while读取整个单词,第二个while跳过空格,循环操作
2.看这段程序
for(j=k;j>=0;j--)
pp[j+1]=pp[j];
pp[0]=xx[l][I]; k++;I--;
程序的算法是从行尾不断读取字符到pp中,但是为了维持单个单词的正向拼写,采用了头插法,即不断向pp开头插入字符的方法获取单词,比如单词four,先是"r",k的值为字符长度+1,k=2,通过循环将现有的字符后移留出空位待插入,循环后变为"rr",插入变为"ur",然后依次变化"uur"->"our"->"oour"->"four",k的作用就是维护当前已获取字符长度的变量,应该是在不断变化的,你把它删了,自然就会出现不可预知的结果了啊
\