lundi 29 juin 2015

Why are my strings changing unintentionally?


I'm making a simple caesar cipher decryption program in C. It takes a string input (stored in text) and should print every possible shift in letters.

If I were to give ABC as input, it should print:

ABC
BCD
CDE
DEF
EFG
...

However, it actually prints:

ABC
BCD
DEF
GHI
KLM
PQR
VWX
CDE
KLM
TUV
...

The code is:

int main(void)
{
    // prompt for plaintext
    string text = GetString();
    string newtext = text;
    for (int k = 0; k < 26; k++)
    {
        for (int i = 0, n = strlen(text); i < n; i++)
        {
            if (text[i] >= 'A' && text[i] <= 'Z')
            {
                newtext[i] = (text[i] - 'A' + k) % 26 + ('A');
            }
            else if (text[i] >= 'a' && text[i] <= 'z')
            {
                newtext[i] = (text[i] - 'a' + k) % 26 + ('a');
            }
        }
        printf("%s\n", newtext);
        printf("%s\n", text);
    }
    return 0;
}

I put printf("%s\n", text); only to debug, and I found that the text string is changing every iteration of the loop, instead of only the newtext string.

Also, I'm including some header files already.

Why is text changing?


Aucun commentaire:

Enregistrer un commentaire