計算機等級考試三級編程解析

字號:

一、替換字符
    函數ReadDat()實現(xiàn)從文件ENG.IN中讀取一篇英文文章,存入到字符串數組xx中;請編制函數encryptChar(),按給定的替代關系對數組xx中的所有字符進行替代,仍存入數組xx的對應的位置上,最后調用函數WriteDat()把結果xx輸出到文件PS10.DAT中。
    替代關系:f(p)=p*11 mod 256 (p是數組中某一個字符的ASCII值,f(p)是計算后新字符的ASCII值),如果原字符的ASCII值是偶數或計算后f(p)值小于等于32,則該字符不變,否則將f(p)所對應的字符進行替代。
    部分源程序已給出,原始數據文件存放的格式是:每行的寬度均小于80個字符。
    請勿改動主函數main()、讀數據函數ReadDat()和輸出數據函數WriteDat()的內容。
    #include
    #include
    #include
    #include
    unsigned char xx[50][80];
    int maxline=0;/*文章的總行數*/
    int ReadDat(void)
    void WriteDat(void)
    void encryptChar()
    {
    }
    void main()
    {
    clrscr();
    if(ReadDat()){
    printf("數據文件ENG.IN不能打開!\n\007");
    return;
    }
    encryptChar();
    WriteDat();
    }
    int ReadDat(void)
    {
    FILE *fp;
    int i=0;
    unsigned char *p;
    if((fp=fopen("eng.in","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;
    fp=fopen("ps10.dat","w");
    for(i=0;iprintf("%s\n",xx[i]);
    fprintf(fp,"%s\n",xx[i]);
    }
    fclose(fp);
    }
    --------------------------------------------------------------------------------
    注:在ReadDat()函數中由于fgets()函數讀入數據時沒有讀入字符串結束符'\0',因
    而用while()循環(huán)在xx數組每一行未尾將換行符'\n'替換成結束符'\0'。
    編寫的函數如下:該函數的基本算法是——讓字符指針pf指向每一行的開頭然后逐一往
    后移動,在移動過程中按要求進行轉換。*pf%2==0用于判斷是否為偶數。if()條件語
    句用于控制不替代字符。
    解法1:
    void encryptChar()
    {
    int i;
    char *pf;
    for(i=0;i{pf=xx[i]; /*每行字符個數*/
    while(*pf!=0)
    {if(*pf%2==0||*pf*11%6<32)
    {pf++;continue;}
    *pf=*pf*11%6;
    pf++;
    }
    }
    }
    解法2:
    void encryptChar()
    {
    int i,j,t;
    for(i=0;i{
    for(j=0;j{
    t=xx[i][j]*11%6;
    if(t<=32 || xx[i][j]%2==0) continue;
    xx[i][j]=t;
    }
    }
    }