c++for-loopoff-by-one

Loop not processing the last character of a string


Basically, the (Vigenere) decryption works perfectly except for not including the final letter for the decryption. For instance, the decryption for m_text yields 48 letters instead of 49. I even tried to manipulate the loop but it doesn't work out well since i will get a out of range exception with .at(). Any help would be appreciated!

using namespace std;
#include <string>
#include <iostream>


int main()

{
  string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  string m_text = "ZOWDLTRTNENMGONMPAPXVUXADRIXUBJMWEWYDSYXUSYKRNLXU";

  int length = m_text.length();

  string key = "DA";

  string plainText = "";

  int shift = 0;

  int shift2 = 0;



//Loop that decrypts
for (int k = 0; k < length-1; k+=2)
    {
      //Key 1 shift
      shift = m_text.at(k) - key.at(0);
      //Key 2 shift
      shift2 = m_text.at(k+1) - key.at(1);

      if (shift >= 0)
        {
          plainText += ALPHABET.at(shift);
        }
      else
        {
          shift += 91;
          plainText += (char)shift;
        }

      if (shift2 >= 0)
        {
          plainText += ALPHABET.at(shift2);
        }
      else
        {
          shift2 += 91;
          plainText += (char)shift2;
        }
    }
 cout << plainText << endl;
}

Solution

  • By the looks of things, you are decoding two characters at a time. So when you have 49 characters in your string, there is one left over (which doesn't get processed). If you make m_text 48 characters long, you will notice you get the correct result.

    It might be easier to replicate your key to match the length of the message, then do character-by-character decoding.