简体   繁体   English

凯撒密码程序的打印结果

[英]Printing result of Caesar cipher program

I'm trying to add "Encrypted message: " before the encrypted message is printed. 我正在尝试在打印加密邮件之前添加"Encrypted message: "

When I put the printf statement inside the "while" loop, I get something along the lines of: AEncrypred message: BEncrypted message: CEncrypted message: etc. 当我将printf语句放入“ while”循环中时,我得到了AEncrypred message: BEncrypted message: CEncrypted message:等。

If I try and put the printf statement outside the loop, nothing prints. 如果我尝试将printf语句放在循环外,则不会输出任何内容。

Is there a way to print "Encrypted message: " before the result while still using putchar(); 有没有办法在仍然使用putchar();在结果之前打印"Encrypted message: " putchar(); ?

#include <stdio.h>
#include <ctype.h>   

char encrypt(char in, int key) 
{
    if (isalpha(in)) 
    {  
        if (isupper(in)) 
        {
            return (((in-'A') + key) % 26) + 'A';
        }
        else 
        {
            return (((in-'a') + key) % 26) + 'a';
        }
    }
    else return in;
}

int main()
{
    int key;
    char ch, res;

    printf("Enter shift amount (1-25):\n");
    scanf("%d", &key);

    printf("Enter message to be encrypted:\n");
    getchar();

    while (ch != '\n') 
    {
        ch = getchar();
        res = encrypt(ch, key);
        putchar(res);
    }
    return 0;
}
#include <stdio.h>
#include <ctype.h>

char encrypt(char in, int key)
{
    if (isalpha(in))
    {
        if (isupper(in))
        {
            return (((in-'A') + key) % 26) + 'A';
        }
        else
        {
            return (((in-'a') + key) % 26) + 'a';
        }
    }
    else return in;
}

int main()
{
    int key;
    char ch, res;
    int checksum = 1;

    printf("Enter shift amount (1-25):\n");
    scanf("%d", &key);

    printf("Enter message to be encrypted:\n");
    getchar();

    while (ch != '\n')
    {
        ch = getchar();
        res = encrypt(ch, key);
        if(checksum) { checksum = 0; printf("Encrypted message: "); }
        putchar(res);
    }
    return 0;
}

I would use that way. 我会用那种方式。 If you don't like it.. let me know. 如果您不喜欢它,请告诉我。 I just solved it on a way that won't violate your code structure. 我只是以不违反您的代码结构的方式解决了它。


Your problem is putting the printf statement inside a loop. 您的问题是将printf语句放入循环中。 The loop will parse your printf statelement ? 该循环将解析您的printf语句? times , until ch equals new line. ,直到ch等于新行。 To prevent that you can use a variable outside the scope, initialized with a value for example 1 . 为防止您可以在范围之外使用变量,并使用例如1的值进行初始化。 To parse the printf statement once you do a condition if that variable equals its number and then assign 0 or another number to it. 要解析printf语句,请在条件为该变量等于它的数字后再为其分配0或另一个数字。 So in the next time the printf has to be parsed, it won't go, because the condition will be false. 因此,在下一次必须解析printf ,它将不会继续,因为条件将为false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM