I have a program that will take in a key. This key shifts the plain text that many number of characters wrapping around z and preserving capitalization. Problems only arise when the ciphertext has the incorrect sized container. Why is the ciphertext
array bigger then my planetext
string?
#import <cs50.h>
#import <stdio.h>
#import <math.h>
#import <string.h>
#import <ctype.h>
#import <stdlib.h>
bool is_number(string str);
void print_string(string call, string s);
// Your program must accept a single command-line argument, a non-negative integer. Let’s call it k for the sake of discussion.
int main(int argc, string argv[])
{
//return error because there was no key given
if (argc == 1 || !is_number(argv[1]))
{
printf("Usage: ./caesar key\n");
return 1;
}
else if (argc != 2){
printf("Usage: ./caesar key\n");
return 1;
}
string plaintext = get_string("plaintext:");
char ciphertext[strlen(plaintext)];
int k = atoll(argv[1]) % 26;
printf("plain Text: %s\n", plaintext);
printf("Text len: %lu\n", strlen(plaintext));
printf("Char len: %lu\n", strlen(ciphertext));
printf("Char 1: %c\n", ciphertext[0]);
printf("key length :%i\n", k);
printf("ciphertext before: %s\n", ciphertext);
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
//isupper
if (isupper(plaintext[i]))
{
//does it go past Z?
if (plaintext[i] + k > 'Z')
{
ciphertext[i] = plaintext[i] + k - 'Z' + 'A' - 1;
}
// does it not go past Z
else
{
ciphertext[i] = plaintext[i] + k;
}
}
//is lower
else if (islower(plaintext[i]))
{
//does it go past z?
if (plaintext[i] + k > 'z')
{
ciphertext[i] = plaintext[i] + k - 'z' + 'a' - 1;
}
// does it not go past z
else
{
ciphertext[i] = plaintext[i] + k;
}
}
// if anything else don't change it
else
{
ciphertext[i] = plaintext[i];
}
}
printf("ciphertext after: %s", ciphertext);
printf("\n");
return 0;
}
The scrambling of the text works just fine. I just don't understand why I'm having some garbage values at the end of some of the unit tests.
This is the output for my code:
plaintext:a
Plane Text: a
Text len: 1
Char len: 6
Char 1:
key length :1 //this is not a tabbing error. This was my output.
ciphertext:b*
plaintext:hello
plain Text: hello
Text len: 5
Char len: 6
Char 1:
key length :12
ciphertext before: n2
ciphertext after: tqxxa
plaintext:asdfjdnghsidkwqd
plain Text: asdfjdnghsidkwqd
Text len: 16
Char len: 6
Char 1:
key length :12
ciphertext before: $
ciphertext after: meprvpzsteupwicp
plaintext:ashdngkdirheknshd
plain Text: ashdngkdirheknshd
Text len: 17
Char len: 0
Char 1:
key length :12
ciphertext before:
ciphertext after: metpzswpudtqwzetp'
The thing I notice is that char len
is 6 until I put in over 16 characters in my plaintext
string. Then it goes down to 0. I assume my problem is here somewhere but I don't know enough about computer science to figure out what is going on. Can you enlighten me?