c - C中交换字母的加密

标签 c loops encryption io alphabet

我需要编写一个程序,从输入中读取一个以新行结尾的句子。该程序应该以字母“a”与“z”、“b”与“y”等交换的方式编写句子的加密。我不应该使用数组,这就是我找不到解决此问题的原因。

这是我的代码:

#include<stdio.h>

int main() {
    char alphabet, temp;
    while( scanf("%c", &alphabet) != '\n') {
        for(char i ='a', j='z'; i <= 'z', j>='a'; i++, j--) {
            if(alphabet == i) {
                temp = j;     
            }     
        }   
        printf("%c", temp);  
    }
    return 0;
}

当我输入:abc 作为输出时,我得到 zyxxxxxxxxxxxxxxxxxxxxxxxxx(无限数量的 x)。

总结一下: 输入:abc。输出:zyxxxxx(无限数量的x)。

最佳答案

你弄乱了 scanf 的返回值:

while( scanf("%c", &alphabet) != '\n'){

当输入的字符(在 alphabet 中)是一个换行符时,您想停止循环。 但是您测试了 scanf 的返回值,它永远不会是 '\n',因为它返回转换字段的数量。

你可以这样尝试:

while( scanf("%c", &alphabet) == 1 && alphabet != '\n'){

关于c - C中交换字母的加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46235638/

相关文章:

c - 使用循环在数组中生成唯一随机数

email - 使用 Apache Camel 进行邮件签名和加密

java - 从 Bouncy CaSTLe 中的文本创建 RSA 公钥时出现问题

c - 我对 int 数组有相同的结构问题

c# - While or and not 等于不工作?

python - 创建动态 Python 字典引用路径

c# - RijndaelManaged 返回空结果

c - Mailx 在 C 程序中?

c - strcat 上的段错误

c++ - 如何使用 Memcpy() 函数