#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int check(int c, string key);
int main(int argc, string argv[])
{
int checkR = check(argc, argv[1]);
if(checkR == 0)
return 0;
string key = argv[1];
string ptext = get_string("plaintext: ");
int len = strlen(ptext);
char ctext[len];
for (int i = 0; i < len; i++)
{
if(isupper(ptext[i]))
ctext[i] = toupper(key[(int)ptext[i] - 65]);
else if(islower(ptext[i]))
ctext[i] = tolower(key[(int)ptext[i] - 97]);
else
ctext[i] = ptext[i];
}
printf("ciphertext: %s\n", ctext);
}
int check(int c, string key)
{
int keyL = strlen(key);
if(c != 2)
return 0;
else if(keyL != 26)
return 0;
for(int i = 0; i < keyL - 1; i++)
{
for(int j = i; j < keyL; j++)
{
if(key[i] == key[j])
return 0;
}
}
return 1;
}
1 Answer
The problem lies here:
for(int i = 0; i < keyL - 1; i++)
{
for(int j = i; j < keyL; j++)
{
if(key[i] == key[j])
return 0;
}
}
When the loop runs the first time, it will always fail because i == j at the start. It's comparing the first letter in the key to itself. It should start with j = i+1.
There may be other problems, but that's why it never gets to the point of accepting input.
Programming notes: When troubleshooting, try inserting some extra unique printf statements to figure out how far the code progresses before terminating. That will at least tell you where to start looking for problems.
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)