从Unix系统创建tr程序的简化版本。翻译字符功能

时间:2015-02-07 23:46:48

标签: c ascii getchar

void Translating(const char set1[], char set2[])
{

    size_t q;
    int s;
    int c;
    unsigned char table[256];

   /*Creates a table to reference characters 
     by their ACII values based on,  
     their integer values in the ASCII table.*/

   for(s = 0; s < 256; s++)
   {
       table[s] = s;

#if 1
       /*Something is occurring here. 
         The values are not returning equal to*/ 
       /*what they should be.*/
       for(q = 0; set1[q] !='\0'; q++)
       {
           if(set2[q] != set1[q])
           table[(int)set1[q]] = set2[q];
       }
#endif

       while((c = getchar()) != EOF)
       {
           putchar(table[c]);
       }
   }
}

在这段代码下面,我有一个工作用户界面(粗略的),它从命令行参数中提取值并将它们保存到set1和set2。这些值通常是一个字符数组(我测试过它们正在被正确复制)。这些字符需要传递给此函数并进行翻译。

For example: `./a asd fgt < test.txt > grr.txt`

这将读入文本文件test并更改

all 'f' with 'a', 
all 'g' with 's' and 
all 't' with 'd'. 

我的功能非常接近工作,但是当我使用它时,我打印的值很疯狂。 好像我的ASCII表增加了一些随机值,如100或其他东西。感谢您的时间,如果有人帮助,任何人都应该尝试这个程序,这是有趣和具有挑战性的。 也许我需要为我的变量重置某个值,C是一个棘手的野兽。

1 个答案:

答案 0 :(得分:1)

   for(s = 0; s < 256; s++)
   {
       table[s] = s;
   }
   for(q = 0; set1[q] !='\0'; q++)
   {
       if(set2[q] != set1[q])
       table[(int)set1[q]] = set2[q];
   }
   while((c = getchar()) != EOF)
   {
       putchar(table[c]);
   }

put both inner `for` and `while` outside the outer `for` loop.

 - First you update the table with all the character list
 - change the character list to your needs.
 - Used the modified character code to print the output.