I have created a program in C. The program is a version substitution string. I have analyzed the program carefully by using the printf statements. My program logic is working correctly. However I am not able to add or concatenate strings.
I am not getting the output from encryptKey function. Why is that? I have earlier being programming in JS and now trying my hand on C.
Here is my code: -
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
string encryptKey(string message);
//stores the cipher word for each alphabet
//used for encryption purposes
char cipher[26];
int main(int argc, string argv[])
{
//Exit the program if no key is added in commandline
if(!argv[1] || argc >= 3)
{
printf("Incorrect or missing command line arguments!\n");
return 1;
}
//checks if there are 26 characters in the decipher key
if(strlen(argv[1]) != 26)
{
printf("Need 26 characters to decipher the key\n");
return 1;
}
//check all the individual characters of the key
for(int i = 0; i < 26; i++)
{
//check if the characters are letters only
if(tolower(argv[1][i]) < 'a' && tolower(argv[1][i]) > 'z')
{
return 1;
printf("All characters should be letters!\n");
}
//checks if each letter exists once
//load the secret key to an array
cipher[i] = argv[1][i];
}
//Asks user for message
string message = get_string("plaintext:");
string secretMessage = encryptKey(message);
//outputs secret message
printf("ciphertext: %s\n", secretMessage);
}
//encrypt the message
string encryptKey(string message)
{
string output = "";
//loop through each alphabet
for(int i = 0; i < strlen(message); i++)
{
char lower = tolower(message[i]);
if(lower >= 'a' && lower <= 'z')
{
//small case starts from location 97
int tempLocation = lower - 97;
if(isupper(message[i]))
{
output += toupper(cipher[tempLocation]);
}
else if(islower(message[i]))
{
output += tolower(cipher[tempLocation]);
}
else
{
output += message[i];
}
}
}
return output;
}
I even tried this to join strings: - strcat(output, toupper(cipher[tempLocation]));
I get this error: -
error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Werror,-Wint-conversion]
strcat(output, toupper(cipher[tempLocation]));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/string.h:130:70: note: passing argument to parameter '__src' here
extern char *strcat (char *__restrict __dest, const char *__restrict __src)
^