코딩/C언어

암호화(시저암호)

런던전통손만두 2019. 9. 17. 17:50
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void printCode(char code[])
{
    int i;
 
    printf("--------------------------------------------------------\n");
    printf("alphabet:\tABCDEFGHIJKLMNOPQRSTUVWXYZ\n");
    printf("encoded:\t");
 
    for (i = 0; i < 26; i++)
        printf("%c", code[i]);
    printf("\n--------------------------------------------------------\n");
}
void makeCode(char code[], int distance)
{
    int i, j = 0;
 
    for (i = 26 - distance; j < 26; i++, j++)
    {
        code[i] = 'A' + j;
 
        if (i >= 25)
            i = -1;
    }
}
void encode(char code[], char sentence[], char encodedSentence[])
{
    int i, index;
 
    for (i = 0; sentence[i] != '\0'; i++)
    {
        if (isalpha(sentence[i]) != 0)
        {
            index = (int)(sentence[i] - 'A');
            encodedSentence[i] = code[index];
        }
        else
            encodedSentence[i] = sentence[i];
    }
 
    encodedSentence[i] = '\0';
}
void clear_stdin()
{
    int ch;
 
    while ((ch = getchar()) != EOF && ch != '\n') {};
}
int main(void)
{
    char code[26];
    int distance;
    char sentence[80], encodedSentence[80];
 
    printf("Enter a distance for encoding: ");
    scanf("%d"&distance);
 
    makeCode(code, distance);
    printCode(code);
 
    //fflush(stdin) 버퍼 비우는 코드인데, 동작을 안한다
    //while (getchar() != '\0'); 오류!
 
    clear_stdin();
    printf("Enter a sentence to encode: ");
    gets(sentence);
    printf("original sentence:\t");
    puts(sentence);
 
    encode(code, sentence, encodedSentence);
    printf("encoded sentence:\t");
    puts(encodedSentence);
}
cs

 

결과:

 

반응형