My code compiles but when I run it I get the error: Segmentation fault (core dumped). I looked at similar questions to this, but I think I'm using isalpha correctly. Any insight will be appreciated. (As an aside, I find my code highly unreadable. If anyone has any tips for me regarding readability and simplicity that would be great!) Here's my code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int cipher(int x);
string k;
string s;
int main(int argc, string argv[]){
if (argc != 2){
printf("I can't do that. argc must be 2.\n");
return 1;
}
string k = argv[1];
for (int i = 0, n = strlen(k); i < n; i++){
if (!isalpha(k[i])){
printf("Vigenere key has non-alphabetical characters.\n");
return 1;
}
}
string s = GetString();
for (int i = 0, n = strlen(s); i < n; i++){
printf("%c", cipher(s[i]));
}
printf("\n");
}
int pos = 0;
int cipherlow(int s);
int cipherupp(int s);
int cipher(int s){
int j = strlen(k);
if(isalpha(s)){
//get pos in keyword
pos = pos + 1;
pos = pos % j;
if(islower(s)){
//print: pos in keyword * shift + s[i]
printf("%c", cipherlow(s));
}
else{
printf("%c", cipherupp(s));
}
}
else{
//just print s[i]
printf("%c", s);
}
return 0;
}
int cipherlow(int s){
int p = k[pos] + s - 97;
p = p % 26 + 97;
return p;
}
int cipherupp(int s){
int p = k[pos] + s - 65;
p = p % 26 + 65;
return p;
}