C语言 从Unix系统创建一个简化版本的tr程序.翻译字符功能


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] !=''; 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语言是个棘手的东西。

   for(s = 0; s < 256; s++)
   {
       table[s] = s;
   }
   for(q = 0; set1[q] !=''; 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.

最新更新