Search code examples
calgorithmcs50caesar-cipher

Coding caesar encryption code asks for key twice?


I implemented the caesar-cipher algorithm but it seems that I didn't catch all the details because when I run the program, it asks for the key to be input twice!

#include <stdio.h>
#include <string.h>
#define SIZE 1024
char text[SIZE];
int text_2[SIZE];
int key;
int encoder(char text[SIZE]){
        printf("plaintext: \n");
        gets(text);
        for (int i = 0; i < strlen(text); ++i) {
            text_2[i] = (int) text[i];
            text_2[i] = text_2[i] + key;
            text[i] = (char) text_2[i];

        }
    return 0;
}

int main() {
    printf("enter the key: \n");
    scanf("%d\n",&key);
    if(key < 26 && key > 0){
        printf("nice!, now enter a word to encrypt it\n");
        gets(text); //this step is necessary to pass text onto encoder function.
        encoder(text);
        puts(text);
    } else{
       printf("Yeuch!!\n");
    }

}

An example of the output is:

enter the key: 
2 //I press 2 and nothing happens, then it asks for it again, hence why I have two 2's
2
nice!, now enter a word to encrypt it
plaintext: 
a
c

Process finished with exit code 0

Solution

  • %d ignores newline character - newline character in stdin will remaining, if your format is %d\n, it needs two enter.

    and gets(text) in if clause removes newline character - you have to do is just change format to %d.

    Solution:

    int main() {
        printf("enter the key: \n");
        scanf("%d", &key);
        if (key < 26 && key > 0) {
            printf("nice!, now enter a word to encrypt it\n");
            gets(text); // this step is necessary to pass text onto encoder
                        // function.
            encoder(text);
            puts(text);
        } else {
            printf("Yeuch!!\n");
        }
    }