Question

A rotation 13 transposition of letters in C++ is not working the way I intended. All the letters were first made upper case, so only the ASCII number 65-90 are relevant. If the letters are above 77, I subtract to account for wrapping back to 'A'.

for (int j = 0; j < plainStr.length(); ++j)
{
  int x = plainStr[j];
// if-statement one
  if(x==32)  // keep spaces
  {
    cryptStr = cryptStr + (char)x;
  }
// if-statement two
  if((x>=65) && (x<=77))  // rotate 'A' through 'M' by +13 
  {
    x=x+13;
    cryptStr = cryptStr + (char)x;
  }
// if-statement three      
  if((x>77) && (x<=90))  // rotate 'N' through 'Z' by -26+13=-13
  {
    x=x-13;
    cryptStr = cryptStr + (char)x;
  }

The problem is that if-statements one and two work as intended by themselves. In fact, if I just do a straight +13 transposition of ASCII without wrapping back to 'A', the code works fine. But, as soon as I incorporate if-statement three, I start to get two-letter outputs that are not right and prevent me from later decrypting. For example:

The input string: "THIS IS ALL I GOTS"

Gives the output: "GUHVIF VIF NAYLYL VI TGBGF"

T = G

H = UH

I = VI

S = F

Please, what am I missing/overlooking???

Was it helpful?

Solution

You need only one of the if statements to execute, so make sure you have the second two in else clauses:

  if(x==32)  // keep spaces
  {
    cryptStr = cryptStr + (char)x;
  }
  else if((x>=65) && (x<=77))  // rotate 'A' through 'M' by +13 
  {
    x=x+13;
    cryptStr = cryptStr + (char)x;
  }
  else if((x>77) && (x<=90))  // rotate 'N' through 'Z' by -26+13=-13
  {
    x=x-13;
    cryptStr = cryptStr + (char)x;
  }

The way you have it now, if the 2nd if gets executed then x is incremented by 13 which makes the 3rd if's condition evaluate to true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top