So in my program I retrieve a command line argument (must be 26 characters with no duplicates) which is used kind of like a rubric for a cypher or something and all these letters are put into an array (i know im not doing it super efficiently).
Following this I prompt for a user to write something and that sentence will in turn change based on what the CLA is inputted as a "cypher" i guess. When i do do this and the cypher is simply just the alphabet (a-z) [therefore should returning the exact same thing written in the prompt] the first couple letters are correct and follow the logic of my code however after getting to the 5th it starts to print out strange random letters for unknown reasons.
ex. hi there how's it going = hi thhrh how's it roisr
plss help :D
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char letters[] = {};
char word[] = {};
// Takes input "Code" and checks if it is suitable (so far) still need to input reminder if no key etc.
int main(int argc, string argv[])
{
if (argc !=2)
{
printf("Missing command-line argument\n");
return 1;
}
else if ((argv[1][1]) == ' ')
{
printf("Usage: ./substitution key");
return 1;
}
else if (strlen(argv[1]) != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
for (int i = 0, n = strlen(argv[1]); i < n; i )
{
if (isalpha(argv[1][i]) != 0)
{
letters[i] = argv[1][i];
}
else
{
printf("Key must only contain alphabetic characters.\n");
return 1;
}
for (int j = 0; j < i; j )
{
if (toupper(argv[1][j]) == toupper(argv[1][i]))
{
printf("No Repeat Characters\n");
return 1;
}
}
// confirmed this prints the entire focking CLA printf("%c", letters[i]);
}
string ptext = get_string("plaintext: ");
printf("cyphertext: ");
for (int j = 0; j < strlen(ptext); j )
{
if (ptext[j] >= 'A' && ptext[j] <= 'Z')
{
int l = ptext[j] - 65;
char z = letters[l];
//printf("%c\n", z);
word[j] = z;
printf("%c", word[j]);
}
else if (ptext[j] >= 'a' && ptext[j] <= 'z')
{
int k = ptext[j] - 97;
char y = letters[k];
word[j] = y;
printf("%c", word[j]);
}
else
{
printf("%c", ptext[j]);
}
}
printf("\n");
}
thats the code!
I've tried debugging and looking into why the value changes however it just suddenly makes letters[k] not equal to e when it should as it is in the array made earlier in the code. I'm not sure what's happening as im pretty sure the code has sound logic
CodePudding user response:
here you have created zero size arrays
char letters[] = {};
char word[] = {};
you need to make them larger. I guess you need
char letters[26] = {};
char word[50] = {};
not quite sure what max size you need tho