You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++项目求助:使用替代字母表加密句子遇到问题

Troubleshooting Your Substitution Cipher Implementation

Hey there! It looks like you're stuck on the encryption step of your substitution cipher project. Let's walk through this step by step, starting with filling in the gaps from your existing code and then getting that encryption working.

First, let's recap your project flow to make sure we're aligned:

  • Input a keyword
  • Remove duplicate characters from the keyword
  • Build a substitution alphabet using the cleaned keyword + remaining unused letters
  • Encrypt a sentence with this alphabet

Step 1: Implement the fixRepeats Function

You've got the function declared, but we need to add code to actually strip out duplicate characters. Here's a straightforward implementation that works with your existing function signature:

void fixRepeats(char array[], int size) {
    int index = 0;
    for (int i = 0; i < size; i++) {
        // Check if current character is already in the cleaned section of the array
        bool isDuplicate = false;
        for (int j = 0; j < index; j++) {
            if (array[i] == array[j]) {
                isDuplicate = true;
                break;
            }
        }
        if (!isDuplicate) {
            array[index++] = array[i];
        }
    }
    // Add null terminator to make it a valid C-style string
    array[index] = '\0';
}

Step 2: Build the Substitution Alphabet

Once we have the cleaned keyword, we need to create a full 26-letter substitution alphabet. We'll start with the keyword, then append any letters from 'a' to 'z' that aren't already included:

void buildSubstitutionAlphabet(const char* cleanedKeyword, char substitutionAlphabet[]) {
    int pos = 0;
    bool usedLetters[26] = {false}; // Track which letters are already in the keyword

    // Add cleaned keyword characters to the alphabet
    while (*cleanedKeyword != '\0') {
        char lowerChar = tolower(*cleanedKeyword); // Normalize to lowercase
        int charIndex = lowerChar - 'a';
        if (!usedLetters[charIndex]) {
            substitutionAlphabet[pos++] = lowerChar;
            usedLetters[charIndex] = true;
        }
        cleanedKeyword++;
    }

    // Fill in remaining unused letters
    for (char c = 'a'; c <= 'z'; c++) {
        int charIndex = c - 'a';
        if (!usedLetters[charIndex]) {
            substitutionAlphabet[pos++] = c;
        }
    }
    substitutionAlphabet[26] = '\0'; // Null-terminate the alphabet array
}

Note: I added tolower() to handle case insensitivity—you can remove this if your project requires strict case matching.

Step 3: Implement the Encryption Function (The Step You're Stuck On!)

This function maps each letter in the input sentence to its corresponding letter in the substitution alphabet. Non-letter characters (spaces, punctuation) stay unchanged:

string encryptSentence(const string& sentence, const char substitutionAlphabet[]) {
    string encryptedResult;
    for (char c : sentence) {
        if (isalpha(c)) {
            bool isUpperCase = isupper(c);
            char lowerChar = tolower(c);
            // Find the index of the original letter in the standard alphabet
            int charIndex = lowerChar - 'a';
            // Get the substituted letter and adjust case if needed
            char substitutedChar = substitutionAlphabet[charIndex];
            encryptedResult += isUpperCase ? toupper(substitutedChar) : substitutedChar;
        } else {
            // Keep non-letter characters as-is
            encryptedResult += c;
        }
    }
    return encryptedResult;
}

Putting It All Together

Here's the full working program that ties all these parts together, including the main function to handle user input:

#include <iostream>
#include <string>
#include <cctype> // For character handling functions
#include <cstring> // For strcpy()
using namespace std;

void fixRepeats(char array[], int size);
void buildSubstitutionAlphabet(const char* cleanedKeyword, char substitutionAlphabet[]);
string encryptSentence(const string& sentence, const char substitutionAlphabet[]);

int main() {
    // Step 1: Get user's keyword
    string keywordInput;
    cout << "Enter a keyword: ";
    getline(cin, keywordInput);

    // Convert keyword to C-style array for fixRepeats
    char keywordArray[100];
    strcpy(keywordArray, keywordInput.c_str());
    fixRepeats(keywordArray, keywordInput.length());

    // Step 2: Build substitution alphabet
    char substitutionAlphabet[27]; // 26 letters + null terminator
    buildSubstitutionAlphabet(keywordArray, substitutionAlphabet);
    cout << "Generated Substitution Alphabet: " << substitutionAlphabet << endl;

    // Step 3: Get sentence to encrypt
    string sentenceInput;
    cout << "Enter a sentence to encrypt: ";
    getline(cin, sentenceInput);

    // Step 4: Encrypt and display result
    string encryptedSentence = encryptSentence(sentenceInput, substitutionAlphabet);
    cout << "Encrypted Sentence: " << encryptedSentence << endl;

    return 0;
}

// Implement fixRepeats
void fixRepeats(char array[], int size) {
    int index = 0;
    for (int i = 0; i < size; i++) {
        bool isDuplicate = false;
        for (int j = 0; j < index; j++) {
            if (array[i] == array[j]) {
                isDuplicate = true;
                break;
            }
        }
        if (!isDuplicate) {
            array[index++] = array[i];
        }
    }
    array[index] = '\0';
}

// Implement buildSubstitutionAlphabet
void buildSubstitutionAlphabet(const char* cleanedKeyword, char substitutionAlphabet[]) {
    int pos = 0;
    bool usedLetters[26] = {false};

    while (*cleanedKeyword != '\0') {
        char lowerChar = tolower(*cleanedKeyword);
        int charIndex = lowerChar - 'a';
        if (!usedLetters[charIndex]) {
            substitutionAlphabet[pos++] = lowerChar;
            usedLetters[charIndex] = true;
        }
        cleanedKeyword++;
    }

    for (char c = 'a'; c <= 'z'; c++) {
        int charIndex = c - 'a';
        if (!usedLetters[charIndex]) {
            substitutionAlphabet[pos++] = c;
        }
    }
    substitutionAlphabet[26] = '\0';
}

// Implement encryptSentence
string encryptSentence(const string& sentence, const char substitutionAlphabet[]) {
    string encryptedResult;
    for (char c : sentence) {
        if (isalpha(c)) {
            bool isUpperCase = isupper(c);
            char lowerChar = tolower(c);
            int charIndex = lowerChar - 'a';
            char substitutedChar = substitutionAlphabet[charIndex];
            encryptedResult += isUpperCase ? toupper(substitutedChar) : substitutedChar;
        } else {
            encryptedResult += c;
        }
    }
    return encryptedResult;
}

Key Notes to Check

  • Don't forget to include <cctype> and <cstring>—they're needed for character handling and string copy functions, respectively.
  • The code handles both uppercase and lowercase letters, but you can tweak the case logic if your project requires strict case sensitivity.
  • If you'd prefer to use std::string instead of C-style arrays for the keyword cleaning, we could refactor that part—just let me know!

内容的提问来源于stack exchange,提问作者J.F.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:26:18