使用数组结构的c++消息编码器

C++ message encoder using an array of structures

本文关键字:c++ 消息 编码器 结构 数组      更新时间:2023-10-16

我编写了一个程序,从文本文件中读取两列字母,并使用这些字母对键盘输入的消息进行编码和解码。我有程序编译,但它只是给我奇怪的白色条,而不是一个编码的消息。我认为我有空函数写正确,但我有点困惑,如何在每个字符读取一次从用户输入的消息。我将在下面给出代码和竞争说明:

使用结构数组对消息进行编码和解码。该结构将有两个元素:一个输入字符和一个输出字符。使用这个数组,程序将对消息进行编码和解码。

你的程序应该有以下函数:

loadArray - this function will read a file containing 26 character pairs.  These pairs will be loaded into an array of 26 rows.  The first value of the pair is the input character and the second is the output character.
encode - this function will take 2 parameters, the array and a single character.  It will return the output character associated with the parameter character.  If no match is found the original character is returned.
decode - this function will be the inverse of the encode function and will match the character parameter with the output character in the array and return the input character, or the original character if no match is found

在main函数中,加载数组后,程序将提示用户输入消息字符串。然后,它将为消息中的每个字符调用encode函数并将其替换为编码后的值,从而对消息进行编码。

要验证结果,请使用已编码的消息并对其进行解码,以确保您得到原始消息。

#include<iostream>
#include<string>
#include<fstream>
#include<array>
#include<iomanip>
#include<stdio.h>
#include<sstream>
using namespace std;
struct code
{
    char input;
    char output;
};

void loadArray(code[]);
void encode(code[], char);
void decode(code[], char);
int main()
{
    code input[26];
    string message;
    char output;

    loadArray;
    // prompt the user for the message
    cout << "Enter your message" << endl;
    cin >> message;

    for (char& c : message) {
        encode(input, c);
    }

    return 0;
}

void loadArray(code c[])
{
    ifstream in("codeFile.txt");
    int i;
    for (int i = 0; i <= 26; i++){
        in >> c[i].input >> c[i].output;
    }

    }
void encode(code c[], char in)
{
    int encMessage;
    int i;
    for (i = 0; i <= 26; i++){
        if (c[i].input == in){
            cout << c[i].output;
            }
    }
}
void decode(code c[], char out)
{
    int decMessage;
    int i;
    for (i = 0; i <= 26; i++){
        if (c[i].output == out){
            cout << c[i].input;
        }
    }
}

进一步的提示:

  • 您尝试将loadArray称为loadArray; -在c++中,您需要括号来调用函数:它应该是loadArray(input);
  • 你的功能编码和解码是void。这是错误的。它们应该返回编码(respp解码)字符,首先是每个要求(它将返回…),然后构建编码字符串