0

So I am using a for loop to pull the specific chars from the key string. Whenever I use a key with the letter "a" or "A", the loop stops. I am using the for loop to pull the char and index with a simple function like this:

#define lowerindex 97    

string k = argv[1];
for (int j = 0; j < strlen(k); j++)
{
    if(isalpha(k[j])
    {
        if(islower(k[j])
        {
            k[j] = k[j] - lowerindex;
        }

...

My guess is that the way I am doing this will return 0 when I get to a letter 'a', but shouldn't it just give it that value '0' to use later rather than terminating the loop?

1

You've hit on the cause, so bonus points for debugging it enough to isolate the issue! Now the explanation. Look at the for loop:

for (int j = 0; j < strlen(k); j++)

On each pass, it calculates strlen(k) and checks that j is less than that. Now, think about what happens when an 'a' is processed. It is converted to binary 0, which happens to also be the end of string marker. So, the next time strlen(k) is calculated, it is changed to the length where that 'a' appeared and the loop ends.

There is a workaround for this, which happens to be more efficient. Set another var equal to strlen(k) as part of the initialization. It means that the calculation is only done once at the start of the loop and will remain intact throughout the run of the loop no matter what is done to k.

    for (int j = 0, sl = strlen(k); j < sl; j++)

Oh, if you plan to use strlen(k) later, then you should actually set the var earlier so that it exists after the loop. ;-)

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 .