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`
这将读取文本文件测试并更改
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] !='\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.
关于从 Unix 系统创建 tr 程序的简化版本。翻译字符功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28388901/