Home > OS >  How do i fix error at f letter and so on at rot13 c program
How do i fix error at f letter and so on at rot13 c program

Time:09-17

i'm new at programming. i'm currently making a rot13 program in c, i tried using "for","if" and it works untill letter f it shows question mark. if i were to write letters from a-z the encrypted results is like : nopqrstuvwxyzabcde???????? . i tried to change the addition/substraction values, the variable, the int. it didn't came out well.

#include<stdio.h>
 
int main()
{
    char message[100], ch;
    int i;
    printf("Enter a message to encrypt: ");
    gets(message);
    for(i = 0; message[i] != '\0';   i){
        ch = message[i];
        if(ch >= 'a' && ch <= 'z'){
            ch = ch   13;
            if(ch > 'z'){
                ch = ch - 26;
            }
            message[i] = ch;
        }
        else if(ch >= 'A' && ch <= 'Z'){
            ch = ch   13;
            if(ch > 'Z'){
                ch = ch - 26;
            }
            message[i] = ch;
        }
    }
    printf("Encrypted message: %s", message);
    return 0;
}

CodePudding user response:

Your code is almost okay. But there is a catch in ASCII. As we know Ascii contains both ASCII (0-127) characters and extended ASCII (128-255) characters. Ascii uses 7 bit for representation whereas extended ASCII uses 8 bit. So, when the value of ch 13 exceeds 127 and you are subtracting 26 from it, it's basically producing a negative decimal number. You can check by print like this printf("%d", ch);. And there is no ascii character associated with negative decimal numbers. That's why it's producing garbage values. You should check before assigning ch = ch 13. Check the below code for reference.

#include<stdio.h>

int main()
{
    char message[100], ch;
    int i;
    printf("Enter a message to encrypt: ");
    scanf("%s", message);
    for(i = 0; message[i] != '\0';   i){
        ch = message[i];
        if(ch >= 'a' && ch <= 'z'){
            if (ch   13 > 'z') {
                ch = ch - 13;
            }
            else ch = ch   13;
        
            message[i] = ch;
        }
        else if(ch >= 'A' && ch <= 'Z'){
            if (ch   13 > 'Z') {
                ch = ch - 13;
            }
            else ch = ch   13;
            message[i] = ch;
        }
    }
    printf("Encrypted message: %s", message);
    return 0;
}

CodePudding user response:

Most likely char is signed on your machine. So ch = ch 13 end up being negative in some cases (e.g. when ch is z). Consequently if(ch > 'z'){ doesn't work as you expect.

Try

int main(void) {
    char ch = 'z';
    ch = ch   13;
    if (ch > 'z')
    {
        puts("Larger");
    }
    else
    {
        puts("Less or equal");
    }
    printf("ch value is %d\n", ch);
    return 0;
}

This may print:

Less or equal
ch value is -121

Use an usigned type or an int for the calculation.

  • Related