当前位置: 动力学知识库 > 问答 > 编程问答 >

c - Creating a simplified version of tr program from Unix system. Translating characters function

问题描述:

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]);

}

}

}

Below this code I have a working user interface(rough one) that pulls in values from command line arguments and saves them to set1 and set2. These values would typically be an array of characters(I have tested them they are being copied correctly). These characters need to be passed to this function and translated.

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

This would read in the text file test and change

all 'f' with 'a',

all 'g' with 's' and

all 't' with 'd'.

My function is very close to working however when I use it my values that are printed are crazy.

As if my ASCII table has been increased by some random value like 100 or something. Thank you for you time if someone helps and anyone should try this program it's fun and challenging.

Maybe I need to reset a certain value for my variables, C is a tricky beast.

网友答案:
   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.
分享给朋友:
您可能感兴趣的文章:
随机阅读: