c - 如何在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
解决方案
- 从输入中逐个字符读取
- 使用简单数组将字符转换为数字或字符串,或使用处理函数
- 打印那个号码
- 替换并不容易,最简单的方法是创建一个临时文件,将数字写入该临时文件,然后将临时文件复制到原始文件并删除临时文件。
_
#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;
}
推荐阅读
- python - 使用 Pegasus 实现迁移学习进行文本摘要生成垃圾字符
- php - 从 php 提供图像时如何防止脚本名称附加到图像文件扩展名
- javascript - 为什么我的自定义 Excel 函数永远不会仅在 Windows 上返回值?
- swift - 将 @EnvironmentObject 属性与 CADisplayLink 一起使用
- postgresql - 如何在 postgresql 中自动导入多个 csv 文件并从其标题创建表?
- swift - SwiftUI Game Center 身份验证不提示用户登录
- crystal-lang - 幸运/水晶初始化错误:过程的未定义方法“信号”
- c++ - 如何正确地将指针传递给函数?
- java - 使用堆的最大和对数组列表
- amazon-qldb - Amazon QLDB 设计原则