C에서 문자열을 '암호화'하는 프로그램을 작성하려고 시도하는 중입니다.이 프로그램의 목표는 사용자가 원래 문자열에서 문자를 교체하는 데 사용할 암호를 입력하여 문자열을 암호화 할 수 있도록하는 것입니다. , 그것을 garbling. 내 원래 프로그램은 사용자 입력 암호를 구문 분석하고 케이스를 유지하는 논리로 이것보다 훨씬 더 복잡했습니다 (모두 놀랍게도 작동했습니다!). 그러나 내가 해결할 수없는 절대적인 기본 문제는 내 '암호화'함수에서 반환 된 문자열이 잘못되었다는 것입니다.
나는 그것을 시도하고 디버깅하기 위해 또 다른 베어 본 버전의 함수를 다시 작성했다. 정보를 찾기 시작하기 전에 이것은 프로그램의 순진한 버전이었습니다.
// Barebones character swap for the encryption program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GET_CHARS_MAX 100
const char plainAlphabet[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
const char prebakedCypher[26] = {'v', 'c', 'h', 'p', 'r', 'z', 'g', 'j', 'n', 't', 'l', 's', 'k',
'f', 'b', 'd', 'q', 'w', 'a', 'x', 'e', 'u', 'y', 'm', 'o', 'i'};
int encryptString(char *encryptStr, int stringLength)
{
for (int i = 0; i < 26; i++) // For each letter in the alphabet
{
for (int j = 0; j < stringLength; j++)
{
if (encryptStr[j] == plainAlphabet[i]) // Find and replace that letter on each pass
{
encryptStr[j] = prebakedCypher[i];
}
}
}
}
int main()
{
char *userString = malloc(GET_CHARS_MAX);
char *stringToEncrypt = malloc(GET_CHARS_MAX);
// Get user input into string
printf("\n Enter a string, 100 characters long maximum: ");
fgets(userString, GET_CHARS_MAX, stdin);
int stringLength = strlen(userString) - 1; // Remove null I think?
// Make a copy of the input to encrypt
strcpy(stringToEncrypt, userString);
printf("\n Copied string: %s", stringToEncrypt);
// Check that indexing the alphabet and cypher actually works
// the way that you think it does
printf("\n Alphabet element 1: %c \n Cypher element 1: %c", plainAlphabet[0], prebakedCypher[0]);
printf("\n Alphabet element 't': %c \n Cypher element 't': %c", plainAlphabet[19], prebakedCypher[19]);
// 'Encrypt' string and display result
printf("\n Plaintext string: %s", userString);
encryptString(stringToEncrypt, stringLength);
printf("\n Encrypted string: %s", stringToEncrypt);
return 0;
}
보시다시피 논리는 매우 간단합니다. 알파벳의 각 문자에 대해 (i)
문자열에서 해당 문자를 찾으면 해당 문자를 (j)
암호의 해당 위치에있는 문자로 대체합니다 (예 : 'a'를 'v'로 대체해야합니다 등). 그러나 출력은 혼란 스러웠습니다.
Enter a string, 100 characters long maximum: this is a string
Copied string: this is a string
Alphabet element 1: a
Cypher element 1: v
Alphabet element 't': t
Cypher element 't': x
Plaintext string: this is a string
Encrypted string: mmfa fa u amoffg
나는 가능한 한 많이 확인하고 싶다 printf
. 문자 배열이 올바르게 인덱싱되는 것처럼 보였지만 올바르게 할당되지 않았습니다 for-loops
( 't'와 'h'는 모두 ' m '이고 'a'에 ' u ' 문자가 할당되는 등 ). 문자 배열을 올바르게 인덱싱하는 방법을 찾고 배열 시작에 대한 추가 포인터를 만든 다음 필요한 요소에 대한 포인터를 따르도록 루프 카운터로 포인터 산술을 수행 하도록 지시하는 게시물을 찾았습니다 . 이것에 대한 나의 무서운 시도는 :
int encryptString(char *encryptStr, int stringLength)
{
char *cypherPointer = &prebakedCypher[0];
for (int i = 0; i < 26; i++) // For each letter in the alphabet
{
for (int j = 0; j < stringLength; j++)
{
if (encryptStr[j] == plainAlphabet[i]) // Find and replace that letter on each pass
{
encryptStr[j] = (*cypherPointer) + i;
}
}
}
}
그냥 쓰레기를 생산합니다.
내가 찾은 간단한 예제에서 사람들 for-loops
은를 사용하여 문자 배열에서 값을 인쇄하고 ptr
그들이 무엇을 / 어떻게 작동하는지 설명하기 위해 사용 했습니다.
나는 초보자이고 아마도 내 문제가 무엇인지 결정하기에는 너무 오랫동안 내 원래 프로그램을 쳐다보고 있었을 것입니다. 누군가 내 논리가 잘못 된 곳을 설명 할 수 있으며 문자 배열의 초기 순진한 인덱싱 (의 요소에 대한 포인터로 이해 charArr[0]
)이 올바른 줄에 있는지 여부를 설명 할 수 있습니까? 근본적으로 내 오해는 문자 배열에 대한 포인터로 무엇을해야하는지, 그리고 그것들에 올바르게 인덱싱 / 할당하는 방법이라고 생각합니다.
감사합니다!
편집 : 문자열이 깨져서 처음에는 프로그램이 작동한다고 생각했습니다. 그런 다음 abcdef
올바른 요소를 읽거나 바꾸고 있는지 확인 하려고 시도 했으며 printf
명령문이 alphabet
및 인덱싱하는 방법을 고려할 때 입력이 예상 한 것과 다르다는 것을 발견했습니다 cypher arrays
.
Enter a string, 100 characters long maximum: abcdef
Copied string: abcdef
Alphabet element 1: a
Cypher element 1: v
Alphabet element 't': t
Cypher element 't': x
Plaintext string: abcdef
Encrypted string: ummdoi
사이퍼에는 반복되는 문자가 없으므로 'b'와 'c'는 모두 ' m '으로 바꿀 수 없습니다 . 우리는 또한 'a'가 ' u '가 아니라 ' v ' 로 대체되어야한다는 것을 알고 있습니다 .
문자열을 제자리에서 교체하고 각 문자를 26 번 확인하고 암호와 시작 문자에 따라 1 ~ 26 번 교체합니다.
예를 들어, 이것이 당신의 예에서 'b'와 'c'가 모두 'm'이되는 이유입니다.
대신 각 문자를 최대 26 번 확인하고 정확히 한 번만 바꿉니다.
int encryptString(char *encryptStr, int stringLength)
{
for (int i = 0; i < stringLength; i++) // For each letter in input
{
for (int j = 0; j < 26; j++)
{
if (encryptStr[i] == plainAlphabet[j]) // Find and replace that letter
{
encryptStr[i] = prebakedCypher[j];
break;
}
}
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다