C密码出错了

问题描述 投票:1回答:2

我正在尝试制作一个C程序,通过按位置“旋转”每个字母来加密消息,根据需要从Z到A回绕,但是我得到了错误的结果。

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

int main(int argc, char* argv[])
{
//Checks if the number of arguments are 2
   if (argc != 2)
   return 1;
   int k;
   int n = strlen(argv[1]);
 //Checks if the second arg(cipher) is a non negative number
   for (int i = 0; i < n ; i++ )
   {
       if (!(isdigit(argv[1][i])))
       {
           return 1;
       }
       k = atoi(argv[1]);
       if (k > 26)
       k = k%26;
       if (k < 0)
       return 1;
  }

unsigned int len_max = 128;
unsigned int current_size = 0;

char *pStr = malloc(len_max);
current_size = len_max;

if(pStr != NULL)
{
int c = EOF;
unsigned int i =0;
    //accept user input until hit enter or end of file
while (( c = getchar() ) != '\n' && c != EOF)
{   

    if (isalpha(c))
    {
        if(isupper(c))
        {
            if ((int)c + k > 90)
            c = (char)((int)c + k - 26);
            c = (char)((int)c + k);
        }
        else
        {
            if ((int)c + k > 122)
            c = (char)((int)c + k - 26);
            c = (char)((int)c + k);
        }
    }
    pStr[i++]=(char)c;

    //if i reached maximize size then realloc size
    if(i == current_size)
    {
        current_size = i+len_max;
        pStr = realloc(pStr, current_size);
    }
}

pStr[i] = '\0';

printf("%s\n",pStr);
    //free it 
free(pStr);
pStr = NULL;
return 0;
}
}

:) caesar.c存在:) caesar.c compiles :)使用1作为密钥将“a”加密为“b”

:(加密“barfoo”为“yxocll”使用23作为键\预期输出,但不是“yxz \ n”

:)使用3作为密钥将“BARFOO”加密为“EDUIRR”:)使用4作为密钥将“BaRFoo”加密为“FeVJss”

:(使用65作为关键\预期输出将“barfoo”加密为“onesbb”,但不是“onrsoo \ n”

:(加密“世界,打招呼!”作为“iadxp,emk tqxxa!”使用12作为关键\预期输出,但不是“umpxp,qmw tqxxm!\ n”

:(处理缺少argv [1] \预期输出,而不是退出代码1

c caesar-cipher edx
2个回答
1
投票

移动单个char将字母'A'..'Z'和'a'..'z'转换为0到25之间的数字。添加k并计算除法的其余部分26:

int c;
while ( ( c = getchar() ) != '\n' && c != EOF )
{   
    if ( !isalpha( c ) )
        continue;

    char firstC = isupper( c ) ? 'A' : 'a';
    int num = (c - firstC + k ) % 26;
    pStr[i++] = (char)(num + firstC); 

    if ( i == current_size-1 ) // -1 because of '\0'
    {
        current_size += len_max;
        pStr = realloc( pStr, current_size );
    }
}
pStr[i] = '\0';

1
投票
if ((int)c + k > 90)
    c = (char)((int)c + k - 26);
c = (char)((int)c + k);

我在这里修改了缩进。想想这部分代码将会做什么,以及可能缺少什么。

© www.soinside.com 2019 - 2024. All rights reserved.