Преобразователь Infix в Postfix + программа оценки правильно печатает в консоль, но неправильно в текстовый файл

Я работаю в Linux над преобразователем инфикса в постфикс для моего класса CSC, и нам нужно направить вывод в текстовый файл для сравнения с выводом нашего инструктора.

Проблема в том, что моя программа печатает правильный вывод, когда я просто запускаю ее в командной строке, но она печатает, казалось бы, случайные символы ASCII в текстовый файл, когда я запускаю ./a.out > output.txt. Мы так выполняли задания весь Квартал, и такое происходит впервые.

Весь мой код ниже, так как я понятия не имею, в чем может быть проблема.

Обратите внимание, что Stack и Queue являются моей собственной разработкой из предыдущих заданий и используют LinkedList в качестве базовой структуры. Все эти назначения работали отлично, поэтому у меня нет оснований полагать, что проблема в них. Кроме того, программа не полностью завершена и еще не учитывает круглые скобки, но уже имеет некоторую логику, которая будет необходима для этого. Эта проблема действительно очень странная.

#include <iostream>
#include <cmath>
#include <cstring>
#include "GenericList.cc"
#include "Stack.cc"
#include "Queue.cc"

using namespace std;

void clear(char[MAX_SIZE]);
Queue<char> infix_builder(char[MAX_SIZE]);
void post_builder(Queue<char>&);//builds the postfix queue
void next_char(Queue<char>&, char);//find the next character's place in the queue
double solution(Queue<char>&);//Solves the equation
bool notop(char);//returns true if the char is not an operator
bool priority(char, char);//returns true if char a has a higher priority than char b
int main()
{
char input[MAX_SIZE];

//erase all values contained by input
clear(input);

//main loop, read each line and process them, one at a time
while(cin.getline(input, MAX_SIZE))
{
    Queue<char> mainq = infix_builder(input);//create a queue from the input
    //cout << "Printing input: " << endl;
    cout << mainq << endl;

    post_builder(mainq);//create the postfix queue
    //cout << "Printing infixed: " << endl;
    cout << mainq << endl;

    cout << solution(mainq) << endl << endl;//solve the equation and print 

    //cleanup
    clear(input);
}
return 0;
}

//clear the char array
void clear(char input[MAX_SIZE])
{
//set all values of a char array of MAX_SIZE to spaces
for(int i = 0; i < MAX_SIZE; i++)
    input[i] = ' ';
}

//Create a queue from the input data
Queue<char> infix_builder(char input[MAX_SIZE])
{
Queue<char> q;
for(int i = 0; ((input[i] != ' ') && (i < MAX_SIZE)); i++)
    q.Enqueue(input[i]);
return q;
}

void post_builder(Queue<char> &q)
{
Queue<char> p;//The postfix queue
Queue<char> pq;//A prioritized queue of operators
//build a post-fixed queue
while(!q.IsEmpty())
{
    char next = q.Dequeue();
    if(notop(next))//if the character is not an operator
    {
        if(((next - '0') >= 0) && ((next - '0') <= 9))//filter out bad char
            p.Enqueue(next);
    }
    else if(next != '(')
    {
        if(pq.IsEmpty())//if it is empty
            pq.Enqueue(next);
        else if(priority(pq.Peek(), next))//if it is time to empty some
        {
            while(!pq.IsEmpty() && priority(pq.Peek(), next))
                p.Enqueue(pq.Dequeue());
            next_char(pq, next);
        }
        else
        {
            next_char(pq, next);
        };          
    }
}

//Empty the rest of the operators into the postfix queue
while(!pq.IsEmpty())
    p.Enqueue(pq.Dequeue());
q = p;
}

double solution(Queue<char>& q)//solves the equation and returns a floating point answr
{
double a;
double b;
Stack<double> stack;

while(!q.IsEmpty())
{
    char next = q.Dequeue();
    if(((next - '0') >= 0) && ((next - '0') <= 9))
        stack.Push((next - '0'));
    else if(next == '+')//perform operator +
    {
        a = stack.Pop();
        b = stack.Pop();
        b += a;
        stack.Push(b);
    }
    else if(next == '-')//perform operator -
    {
        a = stack.Pop();
        b = stack.Pop();
        b -= a;
        stack.Push(b);
    }
    else if(next == '*')//perform * operator
    {
        a = stack.Pop();
        b = stack.Pop();
        b *= a;
        stack.Push(b);
    }
    else if(next == '/')//perform / operator
    {
        a = stack.Pop();
        b = stack.Pop();
        b /= a;
        stack.Push(b);
    }
    else//perform ^ operation
    {
        a = stack.Pop();
        b = stack.Pop();
        stack.Push(pow(b, a));
    }   
}//end while, q is empty, stack.num_items == 1

return stack.Pop();//return the final value pushed onto the stack

}

void next_char(Queue<char>& pq, char next)
{
Queue<char> temp;
while(!pq.IsEmpty() && priority(pq.Peek(), next))/
    temp.Enqueue(pq.Dequeue());
temp.Enqueue(next);//insert next
while(!pq.IsEmpty())//finish copying the Queue
    temp.Enqueue(pq.Dequeue());
pq = temp;//set pq equal to the new queue
}

bool notop(char c)
{
return ((c != '+') && (c != '-') && (c != '*') && (c != '/') && (c != '^') && (c   != '(') && (c != ')'));
}

bool priority(char a, char b)
{
if((b == '+') || (b == '-'))
        return true;//a will always have priority if b is + or -
else if((b == '*') || (b == '/'))
    return ((a == '^') || (a == '*') || (a == '/'));// * and / are equal 
else
    return false;

person jaredad7    schedule 06.11.2013    source источник


Ответы (1)


Когда вы заполняете очередь инфиксов, вы ищете пробелы вместо использования функции cstring "strlen(char[])". Это включает в себя escape-символ \0, который ваш массив символов использует для обозначения конца вашей очереди. Затем этот оператор печатается в файле .txt и дает вам странные символы, на которые вы ссылались. Используйте стрлен().

person jaredad7    schedule 08.11.2013