0

I'd like to loop through the characters in the keyword, transfer them to upper case, subtract by 65, and store in a new string in order to get the values that the letters need to be rotated by. I've been trying to loop through the characters with a for loop, this is the closest I've got.

for (int i = 0, n = strlen(key); i < n; i++)
{
    key[i] = toupper(key[i]);
    int keyvalue = key[i] - 65;
    // test
    printf("%d\n", keyvalue);
}

This prints the correct lowercase values, but one line at a time. They're not being store in a string. How could I save those values in a string/array, also accessible outside the for loop?

1

The toupper() part is working fine, but based on what you're trying to do, you have two issues and a misconception.

Issue 1: You are storing the result of the subtraction in an int called keyvalue, not an array. That means that on every pass through the loop, you will replace the value in keyvalue with the latest calculation. Ultimately, when the loop on the last pass, you will have the numeric value of the last letter from the key stored in keyvalue. If you had declared keyvalue as an array of ints, instead of a single int, then you would be able to save all of the numeric values for the key string, but then there's issue 2.

Issue 2: SCOPE! keyvalue is declared inside the curly braces of the for loop. That means that once the loop ends and you go outside those curly braces, keyvalue ceases to exist. It also means that on every pass through the loop, keyvalue is redeclared on each pass. If you had declared keyvalue outside of the for loop, but inside of main, say at the start, it would persist, whether as an int or as an array. You might want to review class materials on scope.

Misconception: Remember that chars behave and can be treated as one byte signed integers. It isn't required that you assign the result of the math to an int. That means that you could do the subtraction and store the result right back in key and save a little memory by not creating another array: key[i] = toupper(key[i])-65;

And a heads-up. Before you do all that, it would be a good idea to actually store the key string length in a variable if you plan to use it later (which you will). If any letter in the key happens to be a or A, it will store a binary 0 after you do the math. That also happens to be \0, the end of string marker. Do you see how that could be a problem? ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .