If I understand the problem, you need to make an exception for the last characters. I took the opportunity to discard something outside of what is expected.
I made the most idiomatic code C walking a pointer instead of picking up its size. Don’t use the strlen()
where you don’t need.
If you use another data entry mechanism like fgets()
will read the data more appropriately, including space. Scanf()
is only for testing and trivial use.
I did as stated, if other characters need to be treated, you need to stir the code a little to add them. There is no clear criterion for what to do in the case of characters leaving the stated range, I chose to leave as is.
#include <stdio.h>
int main() {
char frase[200];
printf("String: ");
scanf("%200s", frase);
for (char *i = frase; *i != '\0'; i++) *i = *i < 'A' || *i > 'Z' ? *i : (((*i - 65) + 3) % 26) + 65;
printf("String: %s", frase);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
If you want to do not idiomatic, has how, works, technically it is not wrong, but this is not how you do it in C. If you want to do it this way it is better to use another language.
#include <stdio.h>
#include <string.h>
int main() {
char frase[200];
printf("String: ");
scanf("%200s", frase);
for (int i = 0; i < strlen(frase); i++) {
if (frase[i] >= 'A' && frase[i] <= 'Z') { //só altera se estiver na faixa correta
if (frase[i] > 'W') { //trata os casos que precisam girar a tabela
frase[i] += -23;
} else {
frase[i] += 3;
}
}
}
printf("String: %s", frase);
}
I put in the ideone, but I wish I hadn’t written like this.
Try to say what the goal is, the information is too much to understand. I don’t even know what the problem is. Would it be just to make all letters worth 3 misplaced units? The problem is only the last ones? Show what you tried and didn’t work. Do you want to prevent the use of spaces or other characters? If not, what is the criteria to deal with them?
– Maniero
The person writes something and the letters will be worth those below according to the table, yes the problem is only in the last ones, I do not want to prevent the use of space I just do not want the space to appear # (be space)
– WSS
From what I understand you’re wanting to make XYZ become ABC, as I saw in the cipher description of César, what’s happening is when you perform (+ 3) you’re adding up the number according to the ANSI table, so if you take a look at it, the code for Y is different for y, so your if logic didn’t work. Take a look at the ASCII table and you will notice that the next values after Z is [ ]. You can include a logic that when arriving in the last letters (X,Y,Z,x,y,z) it overwrites by (A,B,C,a,b,c). I hope I have helped.
– David Araujo
We still need to know what to do if something is typed out of this range and what you did on
if
that didn’t work out.– Maniero
I will add in the code the if I used, it changes the values but the change is made again this way: X > A > D
– WSS