-1

So I have the code bellow to create an encrypted string using orgTxt and rndTxt, when I debug the code in Visual Studio I get an error of IndexOutOfRangeException in the second for loop.

I check the value of the index with breakpoints and it seems perfectly in range, anyone has an idea what the problem is? If more information needed to help solve this error just leave me comment please.

//variables
    string scrtTxt = null;
    string rndTxt = null;
    string orgTxt = reader.ReadToEnd();

//assigning random a string from key (set of all capital letters) to rndTxt
for (int i = 0; i < fileInfo.Length; i++) 
        {
             rndTxt += key[random.Next(0, key.Length)]; 
        }

//generating the encrypted message scrtTxt
 int j = 0;
 for (int i = 0; i < fileInfo.Length; i++)
       {
            if ((orgTxt[i] + rndTxt[j] - 'A') <= 'Z' && (orgTxt[i] + rndTxt[j] - 'A') >= 'A')
                    scrtTxt += Convert.ToChar((orgTxt[i] + rndTxt[j] - 'A'));

            if ((orgTxt[i] + rndTxt[j] - 'A') > 'Z')
                    scrtTxt += (char)(scrtTxt[i] - 'Z' + 'A' - 1);//IndexOutOfRangeException error here

            j = j + 1 == rndTxt.Length ? 0 : j + 1;
       }
1
  • scrtTxt must be less than i+1 characters long at that point. Double-check it. Commented May 7, 2015 at 6:38

1 Answer 1

5

You are reading from scrtTxt array in this line of code.

scrtTxt += (char)(scrtTxt[i] - 'Z' + 'A' - 1);

Is that what you wanted to do or it should be orgTxt or rndTxt?

Sign up to request clarification or add additional context in comments.

1 Comment

oops my mistake, yes that's the problem, I have to read from orgTxt. Thanks nick-s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.