I've tried so hard for a week to solve this and just can't - despite some attempts from gitter to help me. I've followed some advice to index the keyword before the loop and only use one loop to encipher but I cannot get this code to work. Can anyone please help point me in the right direction?? It passes the check50 checks for all the peripheral stuff but just won't actually encipher the plaintext...Thank you!
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, string argv[])
{
//define result
int result;
//confirm command line argument is one word only, reprompt if not.
if (argc != 2) {
printf("You did not enter one keyword as a command line argument, please start again");
return 1;
}
//confirm command line argument is alphabetical not numeric, reprompt if not.
for (int j = 0, x = strlen(argv[1]); j < x; j++) {
int key = argv[1][j];
if (isdigit(key)) {
printf("You did not enter an alphabetic keyword");
return 1;
}
}
//prompt for plaintext
printf("Enter a string of plaintext for encryption: ");
string s = get_string();
if (s != NULL) {
//initialise index and convert keyletter to lower case then to a = 0 etc
int y = 0;
int k = argv[1][y];
k = tolower(k);
k = k - 'a';
//loop through plaintext
for (int i = 0, n = strlen(s); i < n; i++)
{
int letter = s[i];
//encipher plaintext letter/punctuation etc and print ciphered letter
if (isalpha (letter) && islower(letter)) {
result = ((letter - 'a') + k) % 26;
result = (result + 'a');
}
else if (isalpha (letter) && isupper(letter)) {
result = ((letter - 'A') + (k-32)) % 26;
result = (result + 'A');
}
else {
result = letter;
}
printf("%c", result);
// iterate through keyletters returning to the beginning if plaintext is longer than key
y++;
if (y == strlen(argv[1]))
y = 0;
}
// print final newline
printf("\n");
return 0;
}
}
k = tolower(argv[1][y]) - 'a';
inside your loop? Also, what'sk-32
meant to be? – Blauelf Dec 5 '16 at 13:18isdigit(key)
here, but!isalpha(key)
, otherwise$!?.
would be considered a valid keyword, as it contains no digits. – Blauelf Dec 5 '16 at 13:26