首页 > 解决方案 > 如何在C中用数字替换字母?

问题描述

所以我想为一个学校项目制作一种加密程序,例如,我想用 C 中的 54321 替换字母“a”:12345“b”,我该怎么做?我不是最好的,到目前为止我的代码:

eFile = fopen("Message.txt", "ab+");
            while(!feof(eFile))
            {
                fscanf(eFile,"%c",&message);
            }

例如,如果我将单词 apple 写入文本文件,让程序逐个字母扫描它并用 5 位数字替换每个字母(我已经预定义了它们)例如:apple = 12342 69865 69865 31238 43297

标签: cnumbersletter

解决方案


  • 从输入中逐个字符读取
  • 使用简单数组将字符转换为数字或字符串,或使用处理函数
  • 打印那个号码
  • 替换并不容易,最简单的方法是创建一个临时文件,将数字写入该临时文件,然后将临时文件复制到原始文件并删除临时文件。

_

#include <stdio.h>
#include <assert.h>

int cipher_table[255] = {
    ['a'] = 12342,
    ['p'] = 69865,
    ['l'] = 31238,
    ['e'] = 43297,
    // so on...
};

int main()
{
    FILE *fin = stdin; // fopen(..., "r");
    assert(fin != NULL);
    FILE *fout = stdout; // tmpfile();
    assert(fout != NULL);
    for (int c; (c = getc(fin)) != EOF;) {
        if (c == '\n') {
            if (fputc('\n', fout) == EOF) {
                fprintf(stderr, "Error writing to file fout with fputc\n");
                return -1;
            }
            continue;
        }
        if (fprintf(fout, "%5d ", cipher_table[c]) < 0) {
            fprintf(stderr, "Error writing to file fout with fprintf\n");
            return -1;
        }
    }
    close(fin);
    close(fout);
    return 0;
}

推荐阅读