Encryption with swapping letters in C

1.2k views Asked by At

I need to write a program that reads from the input a sentence terminated by a new line. The program should write an encryption of the sentence in a way that the letter 'a' is swapped with 'z', 'b' with 'y' and so on. I am not supposed to use arrays, that is why I can't find a solution for this problem.

This is my code:

#include<stdio.h>

int main() {
    char alphabet, temp;
    while( scanf("%c", &alphabet) != '\n') {
        for(char i ='a', j='z'; i <= 'z', j>='a'; i++, j--) {
            if(alphabet == i) {
                temp = j;     
            }     
        }   
        printf("%c", temp);  
    }
    return 0;
}

When I input: abc as an output I get zyxxxxxxxxxxxxxxxxxxxxxxxxx(an infinite number of x).

So to sum up: Input:abc. Output: zyxxxxx(infinite number of x).

2

There are 2 answers

3
gsamaras On BEST ANSWER

Compile your code with warnings enabled (e.g. Wall flag)! This:

for(char i ='a', j='z'; i <= 'z', j>='a'; i++, j--)

should give:

warning: left-hand operand of comma expression has no effect [-Wunused-value]

You need to use the logical AND operator && and not a comma between the two comparissons.

Moreover, use getchar() instead, like this:

#include<stdio.h>

int main() {
    char temp;
    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF) {
        for(char i ='a', j='z'; i <= 'z'&& j>='a'; i++, j--){
            if(ch == i){
                temp = j;     
            }     
        }
        if(ch <= 'z'&& ch >= 'a') // do not print if 'ch' is a digit for example
            printf("%c", temp);  
    }
    return 0;
}

Output:

zyx


If you have to use scanf(), then try reading into alphabet, check the return value of scanf, and compare to newline, like this:

while(scanf("%c", &alphabet) != 0 && alphabet != '\n')
5
Gerhardh On

You messed up the return value of scanf:

while( scanf("%c", &alphabet) != '\n'){

You want to stop the loop when the entered character (in alphabet) is a line break. But you test the return value of scanf which will never be '\n' as it returns the number of converted fields.

You could try like this:

while( scanf("%c", &alphabet) == 1 && alphabet != '\n'){