简体   繁体   中英

Caesar cipher for numbers in C

I want to make a Caesar cipher for numbers. (Add 3 to all digits)

Input: 52 Output:85

Input:954 Output:287

Input: -10457 Output:-43780

I'll be very glad if someone helps me with this.


I tried this but when I input the number less than 5 digits it outputs 3 to beginning


When I input 52 it outputs 33385

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

int main() {

int number,operation;

printf("Enter the number: ");
scanf("%d",&number);

printf("%d", ((number/10000)+3)%10);
printf("%d", (((number % 10000)/1000)+3)%10);
printf("%d", (((number % 1000)/100)+3)%10);
printf("%d", (((number % 100)/10)+3)%10);
printf("%d\n", ((number % 10)+3)%10);

printf("press 1 to continue or 2 for exit.");
scanf("%d",&operation);

switch(operation) {
    case 1:
            printf("Enter the number: ");
scanf("%d",&number);

printf("%d", ((number/10000)+3)%10);
printf("%d", (((number % 10000)/1000)+3)%10);
printf("%d", (((number % 1000)/100)+3)%10);
printf("%d", (((number % 100)/10)+3)%10);
printf("%d\n", ((number % 10)+3)%10);


        break;


    case 2:


        break;
}


return 0;

}

Here is the general algorithm:

  • write the number in ASCII into a buffer,
  • iterate over the characters in the buffer,
  • for each character,
    • if it's a digit, add 3,
    • if the resulting ASCII code is bigger than '9', subtract 10

Writing this algorithm in C is an exercise you should perform yourself as part of your educational process. Skipping this exercise, will prevent you to become smarter.

You have first to iterate over every digit of your number.
Then, for each digit, add 3 to the number and use a modulo 10 ( % 10 ) to retrieve only the last digit of your number.
You'll have then to concatenate each digit together to build you caesar-ciphered string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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