Caesar figure, Error in moving letters

0

I'm 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. But I had a problem. If I type the letter A and move to 10 positions, the number 7 will appear, how can I 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;
}
    
asked by anonymous 31.01.2018 / 23:27

1 answer

1

To move to the right you must add instead of subtract. Still the problem persists, which is to get to the edge of the alphabet and start picking up other characters from the ASCII table other than letters of the alphabet. You have to detect when this happens to be able 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 statement that modifies the letter:

nome[i] = (nome[i] + teste - 'a') % TAM_ALFABETO + 'a';
  • Pick up the letter and sum the number of positions (the name teste for the number of positions was not really the best)
  • Subtract 'a' to get a number between 0 and 26
  • Modulate the size of the alphabet to never pass this size
  • Returns 'a' to get a letter between 'a' and 'z'

Let's look at 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'

So z with increase of 3 gives c

See the code working on Ideone

Another alternative is to build a chars array with all valid letters and rotate based on that array. This somewhat simplifies the rotation logic.

    
01.02.2018 / 00:49