用C ++减去ASCII字符/值

时间:2018-09-11 17:23:07

标签: c++ arrays text ascii symbols

这是我编写的代码的功能,它一遍又一遍地减去两个都是字符类型的值,以获得文本,但结果不是字符串文本,而是符号。

我通过 cout 检查了 keyLetters analysis 是否都具有正确的ASCII值和清除字母,然后再将它们转换为 int

lengthText 也是正确的。

键字母是一个由5个字母组成的单词。

void originalText(string analysis, string keyLetters) {
    int lengthText=analysis.length();
    char originText[2000];
    int hold;
    int k;
    for (int i=0; i<lengthText; i++) {
        if(i%5==0)
            k=0;
        hold=keyLetters[k]-analysis[i];
        if (hold<=0) 
            hold*=-1;
        originText[i]=(char)hold;
        cout<<originText[i];
        k++;
    }

}

我得到的结果的屏幕截图:

The result I get

2 个答案:

答案 0 :(得分:3)

keyLettersanalysis都由'a'和'z'之间的字符组成。
这意味着这两个字符之间的差异可以是-25('a'-'z')到+25('z'-'a')。
然后,您要使用ASCII字符来表示这种差异,将负数乘以-1。没有比这更简单的了:

void originalText(string analysis, string keyLetters) {
    int lengthText = analysis.length();
    char originText[2000];
    int hold;
    int k;
    for (int i = 0; i < lengthText; i++) {
        if (i % 5 == 0) {
            k = 0;
        }
        hold = keyLetters[k] - analysis[i];
        if (hold < 0) {
            hold *= -1;
        }
        originText[i] = (char)hold + 'a';
        cout << originText[i];
        k++;
    }
}

您需要通过添加'a'ascii值(即97)来将范围<0,25>中的值移动到可打印的小ascii字符<'a','z'>。 ascii只是控制字符。

这将导致:

  

解密后的文本:
  oncegpmnahioethejewasalihtpegirpehmwantedhoplacallthedacandihedidnmtcareabmuhhejshudcahallinschomlherlarenhsgetangjcatherallhhetimebutihedidnmtcareabmuhhejparentifeelingiwhethejthecareangrymriadiheeaisgchabadgirplehuinohbeashejnefejeverhakecaremfevejchhingarogndcogsharhingfjoocogrlarenhstilpcogshudieiatichooltakealpthatieriogslcbestmfpucknmtheshorcdmesnohfiniihherethereismojetmihthatgirlonedac​​eenhtmschomlwhichiiuniveriitcactualpcbgtleolletendhosacabogtitschmolhhatihiimojecommonandidonnohknmwanyeacthatgirlofcogriewenhtognivejsitymrcollegeifihavetmsacwhenihegohopdejlikeehenshebecameeighheenceariopdsmahuniversitcthereeaiapotmfitudcforhejtodoehichihehohallcicrewgpsmshecjiedandcriedalohahnighhsfhejshecamhmmeandherkindpajentsasqedhejabmuhthereasmnforhejunitmppabpeteajsthaheairgnningouhfjomhejeyesconhinuogspchmwevejsherefgsedtmtellmrsacanyhhingiinceiheeantedtmshayalmnehhatnighthereishwasfglfilledsoathhahnighhshesleltaloneinthedarqeihhmutanconebesideihejtmeahchhejandtmtakecajeofherinhersleepin气喘吁吁的女人和她的家伙当她wawaungersmthecccpessthejrogndshapnotfrmmnm其中bgt因为区域和那个jeaion是cauiehhingieillcomebackholeolleafhejthecdidhheminanctimeeihhmutanceajningmralejt

至于为什么不能给出正确的文本,我将其留给OP,因为我没有这种加密方法。

整个程序:

#include <iostream>
#include <string>
#include <fstream>
#include <cmath>
using namespace std;
string encryptText(string, string);
string cryptanalyzeText(string);
void originalText(string, string);
int main() {
    string text, analysis;
    string key;
    text = "onceuponatimetherewasalittlegirlwhowantedtoplayallthedayandshedidnotcareaboutherstudyatallinschoolherparentsgetangryatherallthetimebutshedidnotcareaboutherparentsfeelingswhethertheyareangryorsadshewassuchabadgirlletusnotbeasherneverevertakecareofeverythingaroundyoustartingfromyourparentstillyoustudiesatschooltakeallthatseriouslybestoflucknothestorydoesnotfinishherethereismoretoitthatgirlonedaywenttoschoolwhichisuniversityactuallybutpeopletendtosayaboutitschoolthatitismorecommonandidonnotknowanywaythatgirlofcoursewenttouniversityorcollegeifihavetosaywhenshegotolderlikewhenshebecameeighteenyearsoldsoatuniversitytherewasalotofstudyforhertodowhichshetotallyscrewupsoshecriedandcriedalotatnightsftershecamhomeandherkindparentsaskedheraboutthereasonforherunstoppabletearsthatwasrunningoutfromhereyescontinuouslyhoweversherefusedtotellorsayanythingsinceshewantedtostayalonethatnightherwishwasfulfilledsoatthatnightshesleptaloneinthedarkwithoutanyonebesideshertowatchherandtotakecareofherinhersleepingasshedidtoherparentsandstudieswhenshewasyoungersothecyclehasgotherroundshapnotfromnowherebutbecauseofareasonandthatreasonisbecausethingswillcomebacktopeopleaftertheydidtheminanytimewithoutanywarningoralert";
    analysis = "qegegrfrafkdittgiiwmurpifvcigutcahayrrtqfkspxcpelxvyidmarrdejvhippfxcmtvebawkledukydkckelxkewctqfphqtgerqpkwgqvrrgdarxhqtrplfjvxiygsytejvhippfxcmtvebawkledrrvezvjjeqnzrgeyyittgixhqarvempxvyatjedejvaaeulghmdrhgutcpefwjrofdvestgirehgiivqtkekqerveahvzedaklizirvogpucogukerfkekfdqdcogtgerqpkwtunccogukydugjeteeysoxvroemncxhmvjiruqlwlkdvwtahcycwpfxhquksrkffiszqkjizkjlhqtvxhqtvmsyqiitakkxhmvxmrxqeidmaninfvfwctqfpwtktliewemvqtjmtkctxumnccbgvgiobnvxezfkssmarfogvzxsojfslfjrxifkjqodgtsmyqeenpkusnzqkonayrryicpxhmvxmrxqwgogtjiwqpkxogpzzeduzxyattslxgxiirkyevqvfwakyyinejvkofqchednzoeijvrstgsicmoviisjkiezavereqchsackynuxvvsuvpxhqtvaaeccstahjxupawsrtgixopqnliojjlefqkelxajgrqyltsauyicdkvhazftviqfrpofckrisjkwffgiwhqerqhaovenpjvvkuputadgexsmubidtgiebawkxhqtvesapwsrtgiynevftpmdcitqciwttckaaetlrnupxsufhismtgiiyqutsnfkeyogucchayvzeduyirqhlwepvfxexnfvsmarryfjzrgekegeejvaazvvhtaukeymnfrefjrxnuiyxhqtnmstyrwfgnwmlxguwomvklafpzkhfuyisxggxaxqeiizvyidmtbaifjfytmppsnqdvwipgjledvfaafeyledcehtavroeociiorjvvizjvvsxgvtizirwstgumdfqyirbciinfurrdevlhiqunlezuyiwmupsuzivvsavyickecihmuxsttgivogpuwhmrestrtfqnayyirqdlxbqerysqqwerqcjsnmpuxhmviiaeqemsngteuegklizijaixntsmqdrgkfqgiobnveffgixhqaumdfjvqizcectuovaifjfytmppaadpzrgatrpedv";

    cout<<"\n1- The original text:\n"<<text;
    cout<<"\n\nEnter a key of type string: ";
    key = "cream";
    cout<<endl;
    cout<<"The text after it has been encrypted:\n"<<encryptText(text, key)<<endl;

    cout<<"\n2- An encrpted text:\n"<<analysis;
    string keyLetters= cryptanalyzeText(analysis);
    cout<<"\n\nThe key is: "<<keyLetters<<endl<<endl;

    cout<<"The decrypted text:\n";
    originalText(analysis, keyLetters);
    cout<<endl<<endl;;

    return 0;
}
string encryptText(string text, string key) {
    int lengthText=text.length();
    int lengthKey=key.length();
    int count=0;

    for (int i=0; i<lengthText; i++) {
        text[i]=key[count];
        if (count<lengthKey-1)
            count++;
        else
            count=0;
    }
    return text;
}
string cryptanalyzeText(string analysis) {
    string keyLetters="aaaaa";
    char ch;
    int i;
    int lengthText=analysis.length();
    for (int keyPlace=0; keyPlace<6 ; keyPlace++) {
        int alphabet[26]={0};
        for (i=keyPlace; i<lengthText; i=i+5) {
            ch=analysis[i];
            alphabet[ch - 'a']++;
        }

        int max=alphabet[0];
        int maxPlace=0;
        for (int j=1; j<26; j++) {
            if(max<alphabet[j]) {
                max=alphabet[j];
                maxPlace=j;
            }
        }
        keyLetters[keyPlace]=maxPlace-4;
        if (keyLetters[keyPlace]<0) 
            keyLetters[keyPlace]+=26+97;
        else
            keyLetters[keyPlace]+=97;
    }
    return keyLetters;
}
void originalText(string analysis, string keyLetters) {
    int lengthText=analysis.length();
    char originText[2000];
    int hold;
    int k;
    for (int i = 0; i < lengthText; i++) {
        if (i % 5 == 0) {
            k=0;
        }
        hold = keyLetters[k] - analysis[i];
        if (hold < 0) {
            hold *= -1;
        }
        originText[i] = (char)hold + 'a';
        cout << originText[i];
        k++;
    }
}

答案 1 :(得分:1)

看来,由于加密文本是由%26(mod 26)生成的,因此大于26的字母的值会丢失其原始值。因此,当它们被解密后,它们被生成为不正确的字母。这就是为什么我必须先减去他们丢失的26个,然后再执行减法程序,因为它将被正确减去。

void originalText(string analysis, string keyLetters) {
    int lengthText=analysis.length();
    char originText[2000];
    int hold;
    int k;
    for (int i = 0; i < lengthText; i++) {
        if (i % 5 == 0) {
            k=0;
        }
        hold = (analysis[i]+26)-keyLetters[k];
        if (hold < 0) {
            hold *= -1;
        }
        hold%=26;
        originText[i] = (char)hold + 'a';
        cout << originText[i];
        k++;
    }
}

结果:

enter image description here