I have a function to convert infix notation to postfix notation. The only problem that I am having is that the last character of the produced postfix notation string is �
�
Any ideas what is happening? This is the function. If I print the infix char* passed as parameter it's printed correctly. It's when I print the postfix char* at the end of the function that I 开发者_JAVA技巧get � for the last character
#include <iostream>
#include <string>
#include <fstream>
#include <string.h>
#include <ctype.h>
#include "queue.h"
#include "stack.h"
#define EXPRESSION_MAX_SIZE 50
#define MAX 10
#define EMPTY -1
using namespace std;
struct stack
{
char data[MAX];
int top;
};
The gibberish character you're seeing is probably the EMPTY
constant you're returning from pop
on an empty stack. Stick an assert(!isempty(s))
in your pop
function to make sure you're not trying to pop from an empty stack. If you run your program in a debugger, the debugger should show you the context (i.e stack trace) where the assert
was triggered.
Trying to pop from an empty container reveals a serious flaw in a program. You shouldn't just return a special value, and hope that the callee bothers to check it. When detecting errors of this sort, it is wise to "fail immediately, and fail loudly". This will make it much easier to pinpoint the cause of errors. It'll also help ensure that bugs are detected before your program is deployed.
In copying line[] to infix[] in main():
for(unsigned int i=0; i<=line.size(); i++)
{
infix[i] = line[i];
}
You failed to null terminate the infix array once you were done copying. The characters you are seeing are what was there at declaration time.
精彩评论