Problem in condition to handle string

Asked

Viewed 97 times

2

It was only supposed to work with lower-case letters and when it arrived at symbols it did not change, but they are being changed. What’s the problem?

 #include <stdio.h>
 int main()
 {
char texto[100];
int i = 0,j = 0,con,tam;
printf("texto\n");
gets(texto);
fflush(stdin);
printf("constante\n");
scanf("%d",&con);
tam = strlen(texto);
char cesar[tam];
for(i = 0; i<tam; i++)
{
    if(texto[i] >= 'a' || texto[i]<= 'z')
        cesar[i] = ( (texto[i] - 97 + con)%26 + 97);
    else
        cesar[i] = texto[i];

    printf("%c",cesar[i]);
}
}
  • You can use the function toupper() (prototype in <ctype.h>) that, well configured, converts 'ç' in 'Ç' for example.

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

4

The problem is the condition that cannot be OR, must be E, the way it was the condition would always be true.

#include <stdio.h>
#include <string.h>
int main() {
    char texto[100];
    int i = 0, con = 0, tam;
    printf("texto\n");
    fgets(texto, 100, stdin);
    printf("constante\n");
    scanf("%d", &con);
    tam = strlen(texto);
    char cesar[tam];
    for(i = 0; i < tam; i++) {
        if(texto[i] >= 'a' && texto[i] <= 'z')
            cesar[i] = ((texto[i] - 97 + con) % 26 + 97);
        else
            cesar[i] = texto[i];
    
        printf("%c", cesar[i]);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I’ve made other important improvements. But there are a few more that could be made.

Browser other questions tagged

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