PostSolvedCaesar cipher in C

Posts 1–8 of 8 · Page 1 of 1
Caesar cipher in C
Hello guys, I found this Caesar cipher on the internet, but he had problems, so I edited it and now it works wonders. Sorry if the notes are in Italian, they are not essential. Tell me what you think ;)
Code:
#include "stdafx.h" //solo se si usa Microsoft Visual Studio
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void cesare(char s, int salto)
{
	char alfabeto[26] = { 'a', 'b', 'c', 'd' ,'e' ,'f' ,'g' ,'h' ,'i' ,'j' ,'k' ,'l' ,'m' ,'n', 'o', 'p' ,'q', 'r', 's' ,'t' ,'u' ,'v' ,'w' ,'x' ,'y' ,'z' };
	int i;

	for (i = 0; i<26; i++)
	{

		if (s == alfabeto[i])
		{
			printf("%c", alfabeto[i + salto]);
			break;
		}
	}

}

//main

int main()

{
	char cript[100];
	int S, lung, i;


	printf("Inserisci la parola da criptare > ");
	scanf("%s", cript); //se si usa Microsoft Visual Studio bisogna andare su Progetto >> Proprietà di *nome progetto* >> C/C++ >> Avanzate >> Disabilita errori specifici >> inserire 4996

	printf("Inserisci il salto da eseguire > ");
	scanf("%d", &S);
	if (S > 26 || S < 0)
	{
		while (S > 26 || S < 0)
		{
			printf("Inserisci il salto da eseguire > ");
			scanf("%d", &S);
		}
	}

	lung = strlen(cript);


	for (i = 0; i<lung; i++)

	{
		cesare(cript[i], S);

	}

	printf("\n");
	system("PAUSE");
	return 0;
}
- - - Updated - - -

I just did a change:
Code:
void cesare(char s, int salto)
{
	char alfabeto[52] = { 'a', 'b', 'c', 'd' ,'e' ,'f' ,'g' ,'h' ,'i' ,'j' ,'k' ,'l' ,'m' ,'n', 'o', 'p' ,'q', 'r', 's' ,'t' ,'u' ,'v' ,'w' ,'x' ,'y' ,'z' ,'a', 'b', 'c', 'd' ,'e' ,'f' ,'g' ,'h' ,'i' ,'j' ,'k' ,'l' ,'m' ,'n', 'o', 'p' ,'q', 'r', 's' ,'t' ,'u' ,'v' ,'w' ,'x' ,'y' ,'z' };
	int i;

	for (i = 0; i<52; i++)
	{

		if (s == alfabeto[i])
		{
			printf("%c", alfabeto[i + salto]);
			break;
		}
	}

}
Quote Originally Posted by System32ita_ View Post
Hello guys, I found this Caesar cipher on the internet, but he had problems, so I edited it and now it works wonders. Sorry if the notes are in Italian, they are not essential. Tell me what you think
You shouldn’t use %s in scanf as you can overflow your text buffer. You should use fgets. If you really want to use scanf you can do %5s which scans the first 5 characters.

Instead of getting the strlen of cript, you can just have a for loop condition where cript[i] != '\0'. Then you don’t have to do an extra loop (strlen is a loop).

Then in your cesare function there is really no need for a loop. You know that there are 26 lower case letters in your array which are sorted. You can just get the decimal value of each character and minus it 97 to get your array index

Also you don’t need to be calling cesare for every character. Why not just parse the entire string?

- - - Updated - - -

Here is a way more efficient Caesar Cipher (I fixed your program). You can make even make it without an array of alphabets. I also realized your code doesn't take into account keys which are less than 0 or greater than 25. It also doesn't print out spaces or non-letter characters (which is also wrong in a Caesar Cipher program). I didn't code the uppercase letters part, maybe you can try implementing that yourself (its only 2-3 additional lines [and no its not adding another array of letters]).

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STR      100

void caesar(char str[], int key);

int main(void) {
	char userString[MAX_STR];
	int key;

	printf("Enter the string (letters only, 100 characters max) to encrypt: ");
	if (fgets(userString, MAX_STR, stdin) == NULL) exit(1);
    
        printf("What is the key: ");
	while (scanf("%d", &key) != 1) {
            printf("What is the key: ");
            scanf("%*s");
    }
    caesar(userString, key);
    
	return 0;
}

void caesar(char str[], int key) {
    
	int i, index, encryptKey;
        int newKey = key % 26;

	for (i = 0; str[i] != '\0'; i++) {
        index = str[i] - 97;
        
        if (index >= 0 && index <= 25) {
                encryptKey = newKey + index;
                if (encryptKey > 25) encryptKey -= 26;
                else if (encryptKey < 0) encryptKey += 26;
            
                printf("%c", (97 + encryptKey));
        
            } else printf("%c", str[i]);
	}
    
    printf("\n");
}
Thanks you, I'm not a good programmer xD
Quote Originally Posted by System32ita_ View Post
Thanks you, I'm not a good programmer xD
It’s cool. Try attempting uppercase characters
Quote Originally Posted by Allura View Post
It’s cool. Try attempting uppercase characters
Ok, I'll do that
Let's optimizie it till the end :P
Code:
#include "stdafx.h"

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

#define MAX_STR      100
#define ALPHABET_SIZE 26
void caesar(char* str, int key);

int main(void) 
{
	char userString[MAX_STR];
	int key;

	printf("Enter the string (letters only, 100 characters max) to encrypt: ");
	if (fgets(userString, MAX_STR, stdin) == NULL) 
		exit(1);

	printf("What is the key: ");
	while (scanf_s("%d", &key) != 1)
	{
		printf("What is the key: ");
		scanf_s("%*s");
	}
	caesar(userString, key);

	return 0;
}

bool isLowerKey(char c)
{
	return c >= 'a' && c <= 'z';
}

bool isUpperKey(char c)
{
	return c >= 'A' && c <= 'Z';
}

void caesar(char* str, int key) 
{
	int i, index, encryptKey;
	int newKey = key % ALPHABET_SIZE;
	int end = strlen(str);
	char cDiff;
	for (i = 0; i < end; i++)
	{
		cDiff = (isUpperKey(str[i]) * 'A') + (isLowerKey(str[i]) * 'a');
		index = str[i] - cDiff;
		if (cDiff == 0)
		{
			printf("%c", str[i]);
			continue;
		}
		encryptKey = newKey + index;
		encryptKey -= (encryptKey >= ALPHABET_SIZE) * ALPHABET_SIZE;
		encryptKey += (encryptKey < 0) * ALPHABET_SIZE;
		encryptKey += cDiff;
		printf("%c", encryptKey);	
	}
	printf("\n");
}
Quote Originally Posted by MikeRohsoft View Post
Let's optimizie it till the end :P
Code:
#include "stdafx.h"

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

#define MAX_STR      100
#define ALPHABET_SIZE 26
void caesar(char* str, int key);

int main(void) 
{
	char userString[MAX_STR];
	int key;

	printf("Enter the string (letters only, 100 characters max) to encrypt: ");
	if (fgets(userString, MAX_STR, stdin) == NULL) 
		exit(1);

	printf("What is the key: ");
	while (scanf_s("%d", &key) != 1)
	{
		printf("What is the key: ");
		scanf_s("%*s");
	}
	caesar(userString, key);

	return 0;
}

bool isLowerKey(char c)
{
	return c >= 'a' && c <= 'z';
}

bool isUpperKey(char c)
{
	return c >= 'A' && c <= 'Z';
}

void caesar(char* str, int key) 
{
	int i, index, encryptKey;
	int newKey = key % ALPHABET_SIZE;
	int end = strlen(str);
	char cDiff;
	for (i = 0; i < end; i++)
	{
		cDiff = (isUpperKey(str[i]) * 'A') + (isLowerKey(str[i]) * 'a');
		index = str[i] - cDiff;
		if (cDiff == 0)
		{
			printf("%c", str[i]);
			continue;
		}
		encryptKey = newKey + index;
		encryptKey -= (encryptKey >= ALPHABET_SIZE) * ALPHABET_SIZE;
		encryptKey += (encryptKey < 0) * ALPHABET_SIZE;
		encryptKey += cDiff;
		printf("%c", encryptKey);	
	}
	printf("\n");
}
Why would you do that. He is clearly trying to learn programming. Let him do it himself.

with char* result, i hope it counts :P
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STR      100
#define ALPHABET_SIZE 26
char* caesar(char* str, int key);

int main(void) 
{
	char userString[MAX_STR];
	int key;

	printf("Enter the string (letters only, 100 characters max) to encrypt: ");
	if (fgets(userString, MAX_STR, stdin) == NULL) 
		exit(1);

	printf("What is the key: ");
	while (scanf("%d", &key) != 1)
	{
		printf("What is the key: ");
		scanf("%*s");
	}
	char* caeserString = caesar(userString, key);
	printf("%s\n", caeserString);
	delete[] caeserString;
	return 0;
}

bool isLowerKey(char c)
{
	return c >= 'a' && c <= 'z';
}

bool isUpperKey(char c)
{
	return c >= 'A' && c <= 'Z';
}

char* caesar(char* str, int key) 
{
	int i;
	int end = strlen(str);
	char* result = (char*)malloc(end + 1);
	char cDiff, encryptKey, newKey = key % ALPHABET_SIZE;
	for (i = 0; i < end; i++)
	{
		cDiff = (isUpperKey(str[i]) * 'A') + (isLowerKey(str[i]) * 'a');
		encryptKey = str[i];
		if (cDiff == 0)
		{
			result[i] = encryptKey;
			continue;
		}
		encryptKey += newKey - cDiff;
		encryptKey -= (encryptKey >= ALPHABET_SIZE) * ALPHABET_SIZE;
		encryptKey += (encryptKey < 0) * ALPHABET_SIZE;
		encryptKey += cDiff;
		result[i] = encryptKey;
	}
	result[i] = '\0';
	return result;
}
Posts 1–8 of 8 · Page 1 of 1
This thread is closed for replies.

Similar Threads

Tags for this Thread

None

Need help?