Декодер, реализующий стек как связанную структуру

Эта программа, которую я пишу, будет использовать специальную реализацию стека в качестве связанной структуры. Закодированное сообщение, введенное пользователем, будет проанализировано и декодировано с использованием стека. То, что я написал, находит компиляцию и работает без сбоев. Программа запрашивает у пользователя строку для декодирования. Однако закодированное сообщение не декодируется с результатом, напечатанным на экране. Я не могу понять, почему моя программа не декодирует и не печатает ввод пользователя. Любая помощь с благодарностью. Благодарю.

Мой заголовочный файл:

#ifndef DECODER_H
#define DECODER_H

#include <iostream>
#include <stdlib.h>
using namespace std;

// ---------------------------
// Structure which will serve
// as the link on the stack.
// ---------------------------
struct StackNode {
char ch;
StackNode* next;
};

// -------------------------------
// Class which will contains the
// functions for appropriate use
// of the stack.
// -------------------------------
class Decoder
{
private:
StackNode* top;

public:
Decoder();
~Decoder();
int EmptyStack();
int FullStack();
void Push(char ch);
char Pop();
void Decode(char *encMsg, char *decMsg);
};

#ifndef FALSE
#define FALSE (0)
#endif

#ifndef TRUE
#define TRUE (!FALSE)
#endif

#endif // End of stack header.

Мой файл .cpp:

#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "Decoder.h"
// ------------------------------
// Function: Decoder()
//
// Purpose: Class constructor.
// ------------------------------
Decoder::Decoder()
{
top = NULL;
}

// ------------------------------
// Function: Decoder()
//
// Purpose: Class destructor.
// ------------------------------
Decoder::~Decoder()
{
// TODO
// Destroy anything remaining in the stack
}

// -----------------------------------
// FullStack()
//
// Return TRUE if the stack is full.
// -----------------------------------
int Decoder::FullStack()
{
return TRUE;
}

// -----------------------------------
// EmptyStack()
//
// Return TRUE if the stack is empty
// -----------------------------------
int Decoder::EmptyStack()
{
return (top == NULL);
}

// ------------------------------------------------
// Function: void Push(char ch)
//
// Purpose: Dynamically creates a structure of type
// StackNode (see Decoder.h), stores the character
// in the structure and pushes the structure onto
// the stack.
// ------------------------------------------------
void Decoder::Push(char ch)
{
// Make a new node whose reference is
// the existing list
StackNode* newNode = new (StackNode);
newNode->ch = ch;
// newNode->next = NULL;
if (top == NULL)
top = newNode; // top points to new node
else
{
newNode->next = top;
top = newNode;
}
}

// --------------------------------------------------
// Function: char Pop()
//
// Purpose: Remove (pop) the top node from the stack,
// copy the character, from this node, delete and
// return the character.
// --------------------------------------------------
char Decoder::Pop()
{
StackNode* temp;
char ch;

if (!EmptyStack())
{
ch = top->ch;
temp = top;
top = top->next;
delete(temp);
return ch;
}
else {
cout << "Warning: Overuse of Pop()" << endl;
return '\0';
}
}

// ----------------------------------------------------
// Function: void Decode(char* encMsg, char* decMsg)
//
// Purpose: Parse and decode the message stored in the
// character array encMsg using the stack functions
// and return the decoded message in the char array
// decMsg.
// ----------------------------------------------------
void Decoder::Decode(char* encMsg, char* decMsg)
{
int StackCount = 0;
char num[2] = " ";
for (int i = 0; i < strlen(encMsg); i++)
{
// check whether 1 is an even number of input
if ((encMsg[i] == '1') && (encMsg[i-1] != '2')) // every other index will be a command number
{
Push(encMsg[i+1]);
StackCount++;
}
if (encMsg[i] == '2' && ((encMsg[i+1] >= '0') && (encMsg[i+1 ] <= '9'))) // every other index will be a command number
{
num[0] = encMsg[i+1];
// pop as many as the argument states to pop
for (int j = 0; j < atoi(num); j++)
{
Pop();
StackCount--;
}
}
}
//cout << StackCount << endl;
// Place the remaining characters from the stack into decMsg
int i;
for (i = 0; i < StackCount; i++)
{
decMsg[i] = Pop();
}
decMsg[i] = '\0';
return;
}

Мой главный .cpp:

#include <iostream>
#include <string>
#include "Decoder.h"using namespace std;

int main (void)
{
char quit[] = "QUIT";
char en[2048];
char dec[512];
Decoder d;

do {
cout << "\nEnter a message to be decoded" << endl;
cin.getline(en, 1024);
d.Decode(en, dec);
cout << dec << endl;
} while (strcmp(en,quit) != 0);

return 0;
}

0

Решение

Эта строка кода

if ((encMsg[i] == '1') && (encMsg[i-1] != '2'))

Может быть, проблема там, когда я равен нулю.

1

Другие решения

Гарантируется, что endMsg [-1] будет выполняться каждый раз, так как сразу за i = 0 следует encMsg [i-1], который всегда проверяется, поскольку && настоящее.

for (int i = 0; i < strlen(encMsg); i++)
{
// check whether 1 is an even number of input
if ((encMsg[i] == '1') && (encMsg[i-1] != '2')) // every other index will be a command number
{
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector