-1

I am trying to write a code on C that can do Caesar Encryption, but the code is not working and I couldn't find any mistakes. It's working neither in terminal nor in repl.it, even if I copy-paste a shared, trusted code and edit a bit to cover my expectations. The program doesn't allow the user to write inputs, except "key" part. It only shows all of the printf functions and that's it.

Here is my code:

#include <stdio.h>
int main() {

    int key, i;
    char text[30], c;

    printf("Please enter a number for key:\n");
    scanf("%d", &key);

    printf("Please enter a text for Caesar-Cipher:\n");
    scanf("%[^\n]s", text);

    for (i = 0; text[i] < '\0'; i++) {
        
        c = text[i];

        if (c>=65 && c<90) {
            c = c + key;
            
            if (c==90) {
                if (key!=0){
                    c = 64 + key;
                }
            }

        text[i] = c;   
        }

        else if (c>=97 && c<122) {
            c = c + key;

            if (c==122) {
                if (key!=0) {
                    c = 96 + key;
                }
            }

        text[i] = c;
        }
    }
    
    printf("The encrypted text is: %s\n", text);

    return 0;
}
Efe
  • 67
  • 6

1 Answers1

0

You are not consuming the newline character, try this:

scanf(" %29s", text);

or if you want space seperated words:

scanf(" %29[^\n]", text);

Also look at this question , scanf() leaves the new line char in the buffer

alex01011
  • 1,670
  • 2
  • 5
  • 17