Cipher works for islower portion but not isupper portion. For instance if I give a key of 3 and enter I like pie!!
to be encrypted, I get O olnh slh!!
I also tried HELLO
and got NKRRU
. The isupper portion is also returning punctuation instead of just letters. I also have not figured out why the original message is being altered to match the cipher message.
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main (int argc, string argv[])
{
/*
Get key from user at command line
Get plaintext from user
Use key to encipher text: c[i] = (p[i] + k)%26
Print ciphered message
*/
string message, cipher;
int key;
// command line, if user doesn't enter 2 arguments return 1 and request a valid
//encryption key and rerun.
if (argc != 2)
{
printf("Please enter a valid encryption key and rerun program.\n");
return 1;
}
else
{
key = atoi(argv[1]);
}
printf("Enter the message you wish to encrypt.\n");
message = GetString();
cipher = message;
int length = strlen(message);
for ( int i = 0; i < length; i++)
{
if (isalpha(message[i]))
{
if (isupper(message[i]))
{
cipher[i] = (message[i] - 'A' + key) % 26 + 'A';
}
else (islower(message[i]));
{
cipher[i] = (message[i] - 'a' + key) % 26 + 'a';
}
}
else continue; //message[i] contains punctuation or a space
}
printf("Your original message was..\n");
printf("%s\n", message);
printf("The encrypted message is...\n");
printf("%s\n", cipher);
return 0;
}
You're overwriting message because you said cipher = message; which means both now point to the same block of memory. Allocate a new output buffer.
And two points to Chux for spotting the superfluous semicolon.
Typo and missing
if
per @interjay.Change
to
With the error, when text was uppercase, both
cipher[i] = (message[i] - 'A' ...
andcipher[i] = (message[i] - 'a' ...
occurred. Givencipher = message
, the cipher was applied twice.@keshlam point about the missing buffer is a significant issue. But I wonder what type
string
is. Is this some sort of C++ lite string? If it is achar *
, code could usecipher = strdup(message);
or