C ++中的Caesar Cipher:如何在没有太多if语句的情况下将消息转换为整数?

时间:2015-09-21 20:49:10

标签: c++

我的comp sci课程的第一个项目涉及制作一个caesar密码程序。我开始将键(字母A-Z)转换为int(0-25)。我需要为包含消息的c风格数组(字符串)执行此操作。我认为我开始做的方法会产生大量的if else语句。有更快的方法吗?

#include <iostream>
#include <proj1.h>
using namesapce std;

//Deciphers a message. cip[] is a char array containing a Cipher message                                                                                                                                    
//as a null-term.                                                                                                                                                                                           
void Decipher(char Cip[], char key);
{
  char intCip[]
  int intKey = 0;
  if(key == A)
    {
      intKey = 0;
    }
  else if(key == B)
    {
      intKey = 1;
    }
  else if(key == C)
    {
      intKey = 2;
    }
  else if(key == D)
    {
      intKey = 3;
    }
  else if(key == E)
    {
      intKey = 4;
    }
  else if(key == F)
    {
      intKey = 5;
    }
  else if(key == G)
    {
      intKey = 6;
    }
  else if(key == H)
    {
      intKey = 7;
    }
  else if(key == I)
    {
      intKey = 8;
    }
  else if(key == J)
    {
      intKey = 9;
    }
  else if(key == K)
    {
      intKey = 10;
    }
  else if(key == L)
    {
      intKey = 11;
    }
  else if(key == M)
    {
      intKey = 12;
    }
  else if(key == N)
    {
      intKey = 13;
    }
  else if(key == O)
    {
      intKey = 14;
    }
  else if(key == P)
    {
      intKey = 15;
    }
  else if(key == Q)
    {
      intKey = 16;
    }
  else if(key == R)
    {
      intKey = 17;
    }
  else if(key == S)
    {
      intKey = 18;
    }
  else if(key == T)
    {
      intKey = 19;
    }
  else if(key == U)
    {
      intKey = 20;
    }
  else if(key == V)
    {
      intKey = 21;
    }
  else if(key == W)
    {
      intKey = 22;
    }
  else if(key == X)
    {
      intKey = 23;
    }
      else if(key == Y)
    {
      intKey = 24;
    }
  else if(Key == Z)
    {
      intKey = 25;
    }
  for( int a = 0; a < str.length(Cip); a = a + 1)
    {


}
char SolveCipher(const char Cip[], char dec[]);
{

}

int main()
{

  return 0;
}

2 个答案:

答案 0 :(得分:4)

char是一个小整数,在ASCII表中所有英文字母都是有序的:B将是A之后的下一个整数,C将在B之后,依此类推。这意味着你可以通过简单的数学获得intKey

int intKey = key - 'A';

答案 1 :(得分:0)

您也可以使用:

#include "stdafx.h"
#include <iostream>

using namespace std;

#define toDigit(k) (k - 'A')

int _tmain(int argc, _TCHAR* argv[])
{
    cout << toDigit('A') << endl;

    system("pause");
    return 0;
}

在ASCII中,A - Z用整数65 - 90表示。如果要将其设置为0 - 25,则只需减去第一个值65即可得到0的值。

示例:

&#39; A&#39; = 65

&#39; A&#39; - &#39; A&#39; = 0

&#39; B&#39; = 66

&#39; B&#39; - &#39; A&#39; = 1

并..............