Justin
Justin

Reputation: 11

All outputs end up the same in C

I'm trying to iterate over key which has been entered into the command line. During the iteration, I want to create 2 strings, upper and lower, which can be used later. The problem is that key, upper and lower are all ending up with the same outputs. Could someone help me figure out where I'm going wrong?

int main(int argc, char *argv[])  
{  
    if (argc != 2)  
    {  
        printf("Usage: ./substitution key\n"); // if no key is entered on command line, end program and say key  
        return 0;  
    }  

    string key = argv[1]; // convert command to key for ease  
    string alpha = "abcdefghijklmnopqrstuvwxyz";  // lowercase alphabet  
    string cap_alpha ="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //uppercase alphabet   
    string lower = argv[1]; // gives string correct length to edit later  
    string upper = argv[1]; // ^ditto  

    if (strlen(key) != 26) // if key is not exactly 26 char, end program and say it must contain 26  
    {  
        printf("Key must contain 26 characters\n");  
        return 0;  
    }  

    for (int i = 0; i < strlen(key); i++) //iterates through key  
    {  
        if (key[i] < 'A' || (key[i] > 'Z' && key[i] < 'a') || key[i] > 'z') //if key includes non alphabet characters, ends command  
        {  
            printf("Key must only contain alphabetic characters.\n");  
            return 0;  
        }  

        else if (key[i] >= 'A' && key[i] <= 'Z')  
        {  
            lower[i] += 32; // if char in key is uppercase, convert to lowercase, add to string "lower"  
            upper[i] = key[i]; // if char in key is uppercase, keeps as uppercase  
        }  
        else  
        {  
            upper[i] = key[i] - 32; // if char in key is lowercase, changes to uppercase  
            lower[i] = key[i];  
        }  
    }  

    printf("key: %s\n", key); // test output  
    printf("lower: %s\n", lower); //test output  
    printf("upper: %s\n", upper); // test output  
}  

Upvotes: 1

Views: 38

Answers (1)

Barmar
Barmar

Reputation: 781004

Assigning strings doesn't make copies, it just assigns a pointer to the same string. So key, upper, lower, and argv[1] are all the same string. When you make a change to one of them, it affects all of them.

You need to make copies first.

size_t len = strlen(key) + 1; // +1 for the null byte
char upper[len], lower[len];
strcpy(upper, key);
strcpy(lower, key);

BTW, C has functions isalpha(), isupper(), islower(), toupper(), and tolower(). You should use these instead of relying on the specifics of ASCII coding.

Upvotes: 3

Related Questions