繁体   English   中英

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

[英]Caesar Cipher in C++: How to convert a message to integers without too many if statements?

我的comp sci类的第一个项目涉及制作一个凯撒密码程序。 我首先将键(字母AZ)转换为整数(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;
}

一个char是一个小整数,在ASCII表中所有英语字母都按顺序排列:B将是A之后的下一个整数,C将在B之后,依此类推。 这意味着您可以使用简单的数学方法获得intKey

int intKey = key - 'A';

您还可以使用:

#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得到您的值。

例:

'A'= 65

'A'-'A'= 0

'B'= 66

'B'-'A'= 1

还有..............

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM