C中的简单加密程序

时间:2014-09-01 17:15:12

标签: c

我必须制作一个将字母和数字改为数字的程序。例如,a = 00,b = 01,c = 03 ... z = 26,0 = 00,1 = 01 ... 9 = 09。这是我的代码到目前为止,但它只更改了我的输入的第一个符号,就像我输入a5235gd它会输出00.任何人有任何想法我的代码有什么问题?

#include <stdio.h>
#include <stdlib.h>
#define N 36

int main( void )
{
    char ch;
    scanf( "%c", &ch );
    const char alp[N] =
    {
       '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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 *enc[N] = 
    {
        "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "00", "01", 
        "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", 
        "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25"
    };

    size_t i = 0;

    while ( i < N &&  ch != alp[i] ) i++;

    if ( i != N ) printf( "%s\n", enc[i] );

    system( "PAUSE" );
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您的代码存在的问题是,它只能读取输入的单个字符,并将该值存储到一个只有一个字符的存储空间的变量中。我建议您查看scanf的手册页,特别注意%s转换规范,以及C字符串和/或字符数组的读取。

http://linux.die.net/man/3/scanf

答案 1 :(得分:-2)

您的程序有很多错误,最好从头开始。这是程序:询问您是否有任何问题。

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

int main()
{
   char str[1000], encrypted[1000], buf[3];
    int num, i = 0;
    scanf("%s", str);              //the user inputs the string or fgets(str, 999, stdin);
    while(str[i]){
        if(isalpha(str[i])){         //check if it is a letter
            num = str[i] - 97;       //using simple ascii table you can see the value of 'a' is 97
            sprintf(buf, "%02d", num); //put the encrypted value in the buffer
            strcat(encrypted, buf);   //concatenate buffer to encrypted
        }
        else if(isdigit(str[i])){      //check if it is a digit
            num = str[i] - '0';        //this gives the value of the number as an integer
            sprintf(buf, "%02d", num); 
            strcat(encrypted, buf);   
        }
        i++;                     //point to the next letter
    }
    printf("%s\n", encrypted);     //print the encrypted message
    return 0;
}