Cipher of César, Error in the displacement of letters

Asked

Viewed 244 times

0

I am trying to make a program that, the user will enter a name and will be asked how many positions the user wants to shift to the right. However, I had a problem. If I type the letter A and move to 10 positions, will appear the number 7, I would have how to solve this?

My code

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

int main(int argc, char** argv)
{
  char nome[100];
  int teste, i;
  printf("Informe um nome:\n");
  scanf("%s", nome);
  printf("Voce quer deslocar a quantas posicoes para a direita:\n");
  scanf("%d", &teste);
  for(i = 0; i < strlen(nome); i++)
  {
     nome[i] = nome[i] - teste;
  }
    printf("%s\n", nome);
  return 0;
}

1 answer

1


To shift to the right you have to add up instead of subtract. Still the problem persists, which is to reach the limit of the alphabet and begin to catch other characters of the ASCII table than letters of the alphabet. You have to detect when this happens in order to calculate the correct letter by doing a rotation:

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

#define TAM_ALFABETO 26 //tamanho do alfabeto definido aqui

int main(int argc, char** argv) {
    char nome[100];
    int teste, i;
    printf("Informe um nome:\n");
    scanf("%s", nome);
    printf("Voce quer deslocar a quantas posicoes para a direita:\n");
    scanf("%d", &teste);

    for(i = 0; i < strlen(nome); i++) {
        if (nome[i] >= 'a' && nome[i] <= 'z'){ //se é minuscula
            nome[i] = (nome[i] + teste - 'a') % TAM_ALFABETO + 'a';
        }
        else {//se é maiúscula
            nome[i] = (nome[i] + teste - 'A') % TAM_ALFABETO + 'A';
        }
    }

    printf("%s\n", nome);
    return 0;
}

Trying to detail the instruction modifying the letter:

nome[i] = (nome[i] + teste - 'a') % TAM_ALFABETO + 'a';
  • Takes the letter and sums the number of positions (the name teste for the amount of positions was in fact not the best)
  • Subtract 'a' to get a number between 0 and 26
  • Module on the size of the alphabet to never pass this size
  • Add back 'a' to get a letter between 'a' and 'z'

Let’s take the same example for the letter 'z' and increase 3:

  • 'z'(122) + 3 gives '}'(125)
  • Subtract 'a'(97) that will give 28
  • 28 % 26 gives 2
  • 2 + 'a' gives 'c'

That’s why z with increase of 3 gives c

See code working on Ideone

Alternatively, build an array of chars with all valid letters and rotate based on this array. This in a way simplifies the logic of rotation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.