Hello,

have the following program code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main (void)
{

char c;
while( (c = getchar()) != '\n')
{   
    putchar(c);
}
putchar ('\n');

return EXIT_SUCCESS;

}

At the moment he reads in entered characters and outputs them again.
I should write it so that it encrypts read-in words / sentences and then outputs them again. The key variable should be fixed and must not be entered by the user.

Example: key: 2; entered word: Good day -> output word: Iwvgp Vci

The entered words should always be written in lowercase letters and spaces must not be encrypted.

My code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main (void)
{

int key = 3;
int letter = 0;
int letter2 = 0;

char c;
while( (c = getchar()) != '\n')
{
    letter = (int)c;
    if((letter + key) > 122)
    {
        letter2 = (letter = 96+key);
    }

/*if (letter == 32)
    {
        letter2 = letter;
    }*/

    else   
    {
        letter2 = letter + key;
    }

    c = (char)letter2;
    putchar(c);
}

putchar ('\n');

return EXIT_SUCCESS;

}

So far, the program encrypts lower case letters, but still has the problem that spaces are encrypted with and capital letters are not yet properly encrypted.

Someone a tip on how I could solve the problem?

This is one of those solved problems. If I were to do this today I'd use one of the over 120 solutions at https://www.rosettacode.org/wiki/Caesar_cipher

If you are getting into commercial software or working on your own app, it's very common to use GPL or open source solutions. In your case, I'd hit Rosetta Code samples.

Something like the following would be a start.

int main(void)
{
    int key = 3;
    int c;
    while ((c = getchar()) != '\n')
    {
        if (isalpha(c))
        {
            c = tolower(c) + key;
            if (c > 'z')
                c -= 26; // c = c - 26
        }
        putchar(c);
    }
    putchar('\n');

    return EXIT_SUCCESS;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.