Letter user determine the size of an array?
Hello all,
I am working on a program called Caesar Cipher which encrypts messages by increasing each character by a value determined by the user (key). It will also roll over if the key rolls over the end of the alphabet.
example) S would translate to U with a key of 2. Z would translate to B with a key of 2.
I have the program almost complete, but I am having one problem. I cannot determine how to let the user determine the size of the array. I assume I need to do this in order to adjust the size of the array according to the message. One of the examples messages to test the project is:
Go ahead, make my day.
If I change the array size to 21 (rather than 80) it will encrypt properly and I will get the encrypted message as:
Jr dkhdg, pdnh pb gdb
The only limit we have is that messages will not exceed 80 characters (I assume I must initialize the size of the array to 80 because of this, correct?). I am having problems encrypting the text properly if the message is < 80. I have to hit enter or input spaces so the message reaches the desired length of 80 before it will then prompt me for the key. Then it will encrypt the message (but of course with all the spaces). How can I determine the size of the array to be the total characters entered by the user even though the initial size is 80? Is there a different approach to this that I am missing?
Here is my code. I apologize as I haven't formatted it yet so I hope its not too difficult to read.
Code:
#include <stdio.h>
int main()
{
char n[80];
int shift;
int i;
int k;
int aSize = sizeof(n)/sizeof(n[0]);
printf("Please enter message:");
for (i = 0; i < aSize; i++)
{
scanf ("%c", &n[i]);
}
printf("Please enter shift amount:");
scanf("%d",&k);
printf("Encrypted message is:");
for (i=0; i < aSize; i++)
{
if ( ( ( n[i] >= 'A' ) && ( n[i] <= 'Z' ) ) || ( (n[i] >= 'a' ) && ( n[i] <= 'z' ) ) )
{
n[i]+=k;
if ((n[i] >= 'Z') && (n[i] <= 'a'))
{
n[i]=((n[i]-'A')) % 26 + 'A';
printf("%c",n[i]);
}
else if (n[i] >= 'z')
{
n[i]=((n[i]-'a')) % 26 + 'a';
printf("%c",n[i]);
}
else
{
printf("%c",n[i]);
}
}
else
{
printf("%c",n[i]);
}
}
return 0;
}
Can anyone give me a hint towards getting this to work right for messages less than 80?