Search code examples
arrayscsearchcs50alphabet

My program just will not recognize letters from alphabetical arrays


So this program won't recognize letters from the arrays of lowercase and uppercase alphabets. I've wasted wayy too many hours on trying to figure this out but I just don't get it.

It seems to recognize only 'a' or 'A' but even that not always.

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>


char ALPHABETLower[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
char ALPHABETUpper[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};


string plaintext = "abcdefghijklmnoprstquvwyzABCDEFGHIJKLMNOPRSTQUVWXYZ";
int i;
int j;
                        

int main(void) {
    for(i = 0; plaintext[i] != 0; i++) {
        for(j = 0; plaintext[i] == ALPHABETUpper[j]; j++)
            printf("%c\n", ALPHABETUpper[j]);
                
        for(j = 0; plaintext[i] == ALPHABETLower[j]; j++)
            printf("%c\n", ALPHABETLower[j]);
    }
}

Solution

  • So I wrestled through and this is the full working version. My mistake before was letting the for-loop run infinitely, unless it could find the character in ALPHABETUpper.

    #include <stdio.h>
    #include <cs50.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    
    char ALPHABETLower[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    char ALPHABETUpper[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
    
    
    string plaintext;
    int i;
    int j;
    
    
    int main(int argc, string argv[2]) {
        for(i = 0; argv[1][i] != 0; i++)
            if(argv[1][i] < 48 || argv[1][i] > 57) {
                printf("Usage: ./caesar key\n");
                return 1;
            }    
        
        plaintext = get_string("Plaintext: \n");
    
        for(i = 0; plaintext[i] != 0; i++) {
            if(isalpha(plaintext[i]) == 0)
                    printf("%c", plaintext[i]);
                    
            for(j = 0; j < 26; j++) {
    
                if(plaintext[i] == ALPHABETUpper[j])
                    printf("%c", ALPHABETUpper[(j + atoi(argv[1])) % 26]);
                        
                if(plaintext[i] == ALPHABETLower[j])
                    printf("%c", ALPHABETLower[(j + atoi(argv[1])) % 26]);
            }
        }
    }