簡體   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