I'm aware that a similar question regarding the same error has been asked before but my situation appears to be different. Here is the specific error:
In my code, I have a function called "is_correct" that checks if the key adheres to the format specified in Pset2 and I think that logically the problem must be coming from there, but I have no idea how. The code runs perfectly fine when I test it and I'm unable to replicate this scenario that check50 keeps encountering. Here is my code:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
bool is_correct(int c, string k);
int char_position(char letter);
string encrypt(string p, string k);
int main(int argc, string argv[])
{
if (is_correct(argc, argv[1]) == true)
{
string p = get_string("plaintext: ");
printf("ciphertext: %s\n", encrypt(p, argv[1]));
return 0;
}
else
{
printf("Error: Incorrect input. Please limit your key to a string of alphabetical characters not exceeding 26 in total\n");
return 1;
}
}
// c == "count" && k == "key"
bool is_correct(int c, string k)
{
bool isco = false;
int ad_asci = 0;
if (c == 2)
{
for (int i = 0, len = strlen(k); i < len; i++)
{
ad_asci += toupper(k[i]);
if (toupper(k[i]) < 65 || toupper(k[i]) > 90)
{
return isco;
}
}
// 2015 is the sum of ASCII values between 'A' to 'Z'
// Therefore k must be 26 characters long, must not have duplicates, etc.
if (ad_asci != 2015)
{
return isco;
}
else
{
isco = true;
return isco;
}
}
else
{
return isco;
}
}
string encrypt(string p, string k)
{
string c = p;
for (int i = 0, len = strlen(p); i < len; i++)
{
if (p[i] > 64 && p[i] < 91)
{
c[i] = toupper(k[char_position(p[i])]);
}
else if (p[i] > 96 && p[i] < 123)
{
c[i] = tolower(k[char_position(p[i])]);
}
else
{
c[i] = p[i];
}
}
return c;
}
// Func will locate char position in alphabet, where 0 is A and 25 is Z
int char_position(char letter)
{
string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string b = "abcdefghijklmnopqrstuvwxyz";
int position = 0;
if (letter > 64 && letter < 91)
{
for (int i = 0, len = strlen(a); i < len; i++)
{
if (letter == a[i])
{
position += i;
break;
}
}
}
else
{
for (int i = 0, len = strlen(b); i < len; i++)
{
if (letter == b[i])
{
position += i;
break;
}
}
}
return position;
}