If I understand the problem, you need to make exception for the last characters. I used to discard something out of what is expected.
I made the most idiomatic code C by walking a pointer instead of taking its size. Do not use strlen()
where you do not need .
If you use another data entry mechanism like fgets()
it will read the data more appropriately , including space. Scanf()
is only for testing and trivial use.
I did according to the statement, if other characters need to be dealt you need to tinker with the code to add them. It does not have a clear criterion of what to do in cases where there are characters that leave the range, I chose to leave it as it is.
#include <stdio.h>
int main() {
char frase[200];
printf("String: ");
scanf("%200s", frase);
for (char *i = frase; *i != '#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++) {
*i = *i < 'A' || *i > 'Z' ? *i : (((*i - 65) + 3) % 26) + 65;
}
printf("String: %s", frase);
}
See running on ideone . And at Coding Ground . Also put it in GitHub for future reference .
If you want to do not idiomatic, it has like, it works, technically it's not wrong, but that's not the way it's done in C. If it's to do it this way it's better to use another language.
#include <stdio.h>
int main() {
char frase[200];
printf("String: ");
scanf("%200s", frase);
for (char *i = frase; *i != '#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++) {
*i = *i < 'A' || *i > 'Z' ? *i : (((*i - 65) + 3) % 26) + 65;
}
printf("String: %s", frase);
}
I voted for ideone , but I would rather not have written like this.