ASCII characters and table

Asked

Viewed 373 times

0

I am trying to perform a URI exercise ,and in the 1 part it asks the following:

In the first step, only characters that are lower case letters and capital letters shall be moved 3 positions to the right according to table ASCII: letter 'a' should turn letter’d', letter 'y' should turn character '|' and so on

However he is also changing the ones that do not come out lowercase and uppercase ,I do not know why this is happening,I thank those who can help.

For example: incoming texto #3 should get out wh{wr #3 ,but it’s coming off wh{wr <

#include <stdio.h>
#include <string.h>
int main(){
char x[10],y[10];
int i,qnt;
fgets(x,sizeof(x),stdin);
qnt = strlen(x);

 /********   1 PASSADA  ************/
 for(i = 0;i<qnt;i++){
    if (((x[i]>=65) && (x[i]<=90))  || ((x[i]>=97) && (x[i]<=122)) )
            y[i]=x[i]+3;
            printf("%d %d , %c \n",i,y[i],y[i]);
 }

 printf("tamanho da string %i \n",qnt);

 printf("normal %d , %s\n",x,x);
  printf("1 passada  , %s \n",y);

 printf("normal %d , %s\n",x,x);
 for(i = 0;i<qnt;i++){
    printf("%d %d , %c \n",i,x[i],x[i]);

 }
 }

1 answer

1


Actually the program is not setting values for when it is not a letter, thus picking the default value that is in the vector y.

Change your for for:

for(i = 0; i<qnt; i++)
{
    if (((x[i]>=65) && (x[i]<=90))  || ((x[i]>=97) && (x[i]<=122)) )
        y[i]=x[i]+3;
    else //faltou este else
        y[i]=x[i]; //que atribui o valor original quando não é letra

    printf("%d %d , %c \n",i,y[i],y[i]);
}

Confirm in Ideone that you already get the expected output

Some remarks I leave:

  • If you have the main as int shall put the return value at the end with return 0; indicating that the program ended successfully

  • Putting the ascii value of the letters directly is harmful to reading the code. Instead you should put the letter as char. Soon the if within the for would be better written like this:

    if ((x[i]>='A' && x[i]<='Z')  || (x[i]>='a' && x[i]<='z') )
        y[i]=x[i]+3;
    
  • In printf("normal %d , %s\n",x,x); is printing the string x as a whole with %d that makes no sense.

  • The fgets leave him one \n at the end of the reading within the string. If you do not want it or it is imperative that you do not have it, remove it. You can see in this my other answer how to do it.

  • Thanks for the quick reply!!. will make the changes, relative to the printf imprinting the string with %d I put only to see how it was /if it was possible. Thank you so much for the tips.

Browser other questions tagged

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