0

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).

Fabio
  • 336
  • 3
  • 17
Marija Lyka
  • 163
  • 3
  • 17

2 Answers2

3

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'){
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
2

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')
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • `printf("%c", temp);` : It is also used when the entered characters are not alphabetic lowercase letters. It may be an uninitialized value. or it may be the most recent value. – BLUEPIXY Sep 15 '17 at 09:11
  • `scanf` can return `EOF` which can be non-zero. Test succesful matches `== 1` instead of doing `!= 0`. – user694733 Sep 15 '17 at 09:27
  • 1
    But what if i input "abc cba". Then I get "zyxxxyz". Where does the space go? – Marija Lyka Sep 15 '17 at 09:27