The feedback to my last code example was great, that's why I want to ask a few things again.
I wrote a program that applies the so-called Caesar shift(+13) to a input text.
But I wonder how I should use fgets() better. First I've used gets(), but this method gives you uncontrolled array overflows. So I switched to fgets() and figured that when the array size is smaller then the amount I put in, fgets() always write so much characters in the array that is possible and the rest stays in the input buffer.
I used the 2nd answer for my problem - fseek: How to clear input buffer in C? - Stack Overflow
Of course I could just increase the buffer to a huge amount, but what do you say? What is the best solution for this?
How I understand fseek, I put the FILE* Pointer to SEEK_END with zero offset, so the data is still in the buffer. I guess with a new fgets-call it will be get deleted?
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_LENGTH 3
#define SHIFT 13
void Caesar(char s[]);
int main(void)
{
char s[MAX_LENGTH];
int c;
puts("\nType in the text(max. 100 characters) you want to encrypt: ");
while(fgets(s, MAX_LENGTH, stdin) != NULL) // reads string with certain length "MAX_LENGHT" from stdin and writes it in character array s
{
if (s[strlen(s) - 1] == '\n') // delete the added newline character '\n' and replace it with terminating zero '\0'
s[strlen(s) - 1] = '\0';
puts("\nEncrypted: ");
Caesar(s);
puts(s);
puts("\nDecrypted: ");
Caesar(s);
puts(s);
puts("\nType in the text(max. 100 characters) you want to encrypt: ");
fseek(stdin, 0, SEEK_END);
}
return 0;
}
/*
* Encrypts text by replacing each character with its 13th right neighbour.
* By applying Caesar() two times on a text gives you the original string.
*/
void Caesar(char s[])
{
int buffer=0;
int i=0;
while (s[i] != '\0')
{
if (s[i] >= 'a' && s[i] <= 'z') //only encrypt/decrypt for lower-case letters
{
s[i] = (s[i] - 'a' + SHIFT) % 26 + 'a'; //encrypt (or decrypt) the letter s[i]
}
i++;
}
}