-2

好的,所以我正在为课程编写一个程序,但我对 c++ 的方式不是很熟悉。我研究了 char 数组,但无法找出问题所在。在分配空间时,似乎没有在所需位置分配空终止符。

我的问题是这个。我正在分配一个数组,如下所示:

char* St ="";

if(P.GetSize() > 0)
{
    int StLen = P.GetSize() + 1;
    St= new char[StLen];

    int i;
    for( i = 0;!P.isEmpty() && i < (int)strlen(St); i++)//StLen
    {
        *(St+i)= P.getTop();

        P.Pop();
    }
    *(St+i) = 0;
    std::reverse( St, &St[ strlen( St ) ] ); //flip string to display bottom to top
}

如果 P.GetSize() 为 1,并且我为空终止符添加了一个,则 (int)strlen(St) 行仍然返回 16 的长度,这是我读入的数组的原始长度。我在下面发布了我的工作程序供其他有相同问题的人参考

下面是我的工作解决方案头文件:

 //Created By : Timothy Newport
//Created on : 4/26/2012
//===========================================
// NewportStack.h
//============================================
#pragma once

#include <iostream>
#include <iomanip>
#include <fstream>
#include <crtdbg.h>
#include <stack>
#include <string>
using namespace std;

const int MAX_POSTFIX = 30;
void infixToPostfix(const char *infix, char* postfix,ostream& os);
void WriteHeader(ostream& os);
void WriteResults(ostream& os,const char *postfix);

template<class T>
struct Node
{
    T data;
    Node<T> *prev;
};

template<class T>
class NewportStack
{
    private:        
        Node<T> *top; 
        int size;
    public:
        NewportStack();
        NewportStack(const NewportStack <T> & displayStack);
        ~NewportStack();
        void Push(T ch);
        void Pop();
        T getTop() const;
        bool isEmpty() const;
        const int GetSize() const;
        int SetSize(const int prvSize);
        bool checkPresidence(T data,char infix);
        void printStack() const;

        virtual ostream& Output (ostream& os, const NewportStack & S,
                                    const char infix,const char *postfix
                                    ,const int size) const;
};

//------------
//Constructor
//------------
template<class T>
NewportStack<T>::NewportStack()
{
    top = NULL;
    size = 0;
}
template<class T>
void NewportStack<T>::printStack() const
{
    Node<T>* w;
    w = top;
    while( w != NULL )
    {
        cout << w->data;
        w = w->prev;
    }
}
//------------
//Copy Constructor
//------------
template<class T>
NewportStack<T>::NewportStack(const NewportStack<T> &Orig)
{
    if (Orig.top == NULL) // check whether original is empty
    {
        top = NULL;
    }
    else
    {
        Node<T>* newPrev=new Node<T> ;

        Node<T>* cur = Orig.top;
        newPrev->data = cur->data;
        top = newPrev;
// Now, loop through the rest of the stack
        cur = cur->prev;        
        while(cur != NULL )
        {
            newPrev->prev = new Node<T>;
            newPrev = newPrev->prev;            
            newPrev->data = cur->data;  
            cur = cur->prev;
        } // end for        
        newPrev->prev = 0;
        cur = 0;

    } // end else
    size = Orig.size;
} // end copy constructortor

//------------
//DeConstructor
//------------
template<class T>
NewportStack<T>::~NewportStack()
{
    Node <T>* w = top;

    while(top!=NULL)
    {
        delete w;
        top=top->prev;
    }
    size =0;
}
//------------
//getsize
//------------
template<class T>
const int NewportStack<T>::GetSize() const
{
    return size;
}
//------------
//SetSize
//------------
template<class T>
int NewportStack<T>::SetSize(const int prvSize)
{
    return size = prvSize;
}
//------------
//Push
//------------
template<class T>
void NewportStack<T>::Push(T d)
{
    Node <T>* w= new (std::nothrow) Node<T>;

    if ( !w ) 
    {
       cerr << "Error out of memory in Push\n";
       exit (1);
    }
    w->data =d;

    if( top == NULL )
    {
        w->prev = NULL;
    }
    else
    {   
        w->prev = top;
    }
    top = w;
    w = NULL;
    size++; 
}

//------------
//Pop
//------------
template<class T>
void NewportStack<T>::Pop()
{   
    if( top == NULL )
        return;
    Node<T>* w = top;
    top = top->prev;
    delete w;
    w = NULL;
    size--;
}
//------------
//getTop
//------------

template<class T>
T NewportStack<T>::getTop() const
{
    if (isEmpty ()) 
        exit(0);
    return top->data;
}

//------------
//isEmpty
//------------
template<class T>
bool NewportStack<T>::isEmpty() const
{
    if(top == NULL)
    {
        return true;
    }
    return false;
}

//------------
//checkPresidence
//------------
template<class T>
bool NewportStack<T>::checkPresidence(T data,char infix)
{
    switch(infix)
    {
        case '+': case '-':
            switch(data)
            {
                case '+': case '-': case '*': case '/': case '%':
                         return true;
                default: return false;
            }           
        case '*': case '/': case '%': 
            switch(data)
            {
                case '*': case '/': case '%':
                       return true;
                default: return false;
            } 
        default: return false;
    }
}

//------------
//OutPut
//------------
template<class T>
ostream& NewportStack<T>::Output(ostream& os, const NewportStack<T>& S,
                                    const char infix,const char *postfix
                                    ,const int size) const
{
    NewportStack<T> P ( S );//***INVOKED COPY CONSTRUCTOR*****

    char* St = new char[21];

    int i;
    if(P.GetSize() > 0)
    {
        int StLen = P.GetSize();

        for( i = 0;!P.isEmpty();i++)
        {
            *(St+i)= P.getTop();

            P.Pop();
        }
        *(St+i) = 0;
        std::reverse( St, &St[ strlen( St ) ] ); //flip string to display bottom to top
    }
    else
        *(St+0) = 0;

    os <<left<<setw(20) << infix ;

    for(i = 0;i < (int)strlen(St);i++)
    {
        os << St[i];        
    }
    os << right<< setw(21-i);

    for(i = 0;i <size;i++)
    {
        os << postfix[i];       
    }
    os << endl;

    if(St != NULL)
    {
        delete[] St;
    }

    return os;                                      
}

CPP文件在这里:

//Created By : Timothy Newport
//Created on : 4/26/2012
//===========================================
// NewportStackTester.cpp
//============================================
#include "NewportStack.h"
//------------
//Main
//------------
int main()
{
    //////////////////////////////////////////
    ///  Tester Part Two Test The class ///
    //////////////////////////////////////////

    char arr[] = "a+b-c*d/e+(f/g/h-a-b)/(x-y)*(p-r)+d";
    //char arr[] = "a+b-c*d/e+(f/g)";

    int len = (int) strlen(arr);
    char *postfix = new char[len+1];

    ofstream outputFile;
    outputFile.open("PostFix.txt");

    outputFile << "Infix is : " << arr<<endl<<endl;
    WriteHeader(outputFile);

    _strupr( arr); ///**** convert the string to uppercase ****

    infixToPostfix(arr,postfix,outputFile); 

    outputFile.close();



    system("notepad.exe PostFix.txt");

    return 0;
}
//------------
//infixToPostfix
//------------
void infixToPostfix(const char *infix, char* postfix, ostream & os) 
{   
    NewportStack <char> P;
    int len=strlen(infix);
    len += 1;
//  cout << "infix in infixToPostfix: " << infix << endl; 
    int pi = 0;
    int i=0;
    char ch;

   while( i < len && *(infix+i) !='\0')
   {
       ch = *(infix+i);

      if(ch >='A' && ch <='Z' )
      {
            postfix[pi++]= ch;
      }
      else if(ch =='+' ||ch =='-'||ch =='*'||ch =='/'||ch =='%')
      {       
            while(!P.isEmpty() && P.getTop() != '(' 
                && P.checkPresidence(P.getTop(), ch ) )
            {               
                postfix[pi++]= P.getTop();
                postfix[pi] = 0;                
                P.Pop();
            }

            P.Push(ch);         
       }
      else if(infix[i] == '(')
      {
            P.Push(infix[i]);
      }
      else// if(infix[i]==')')
      {
        while(!P.isEmpty() && P.getTop() != '(')
        {
            postfix[pi++] = P.getTop();
            P.Pop();
        }
        P.Pop(); //****remove the '(' from the stack top.
      }

     P.Output(os, P, ch, postfix, pi); // display after each read

     i++;    
   }
   // end of infix empty stack
   while(!P.isEmpty() )
   {
        postfix[pi++]= P.getTop();
        P.Pop();
   }
   postfix[pi] = 0; //add null terminator at the end of the string.
   //cout << "postfix 104: " << postfix << endl;
 P.Output(os,P,*infix,postfix,pi);// display final line
 WriteResults(os,postfix);
}
//------------
//WriteHeader
//------------
void WriteHeader(ostream& os)
{
    os <<left<< setw(20)<< "Input Characters" << setw(20)<< "Stack Item" << setw(20)
                << "PostFix" <<endl <<setw(20)<< "----------------"<< setw(20) 
                << "----------" << setw(20)<< "-------" <<endl;
}
//------------
//WriteResults
//------------
void WriteResults(ostream& os,const char *postfix)
{
    os << endl<< "The Final postfix is: " << postfix <<endl;
}

你们帮了我很多!我一直在弄乱它,直到我发现主要问题。

4

2 回答 2

3

new char[StLen];不初始化内存。您应该使用std::string而不是像这样手动处理字符数组。

如果您被迫手动使用字符数组,您可以编写自己的自动内存管理包装器来处理释放'\0',并且您可以通过在第一个索引处写入一个字符来将内存初始化为以空字符结尾的字符串。

于 2012-05-02T04:37:40.237 回答
0

我首先想到的是,除非您绝对确定它是一个以零结尾的字符串,否则您不能在 char 数组上使用 strlen()。在您的循环条件中,您应该检查 (i < (StLen - 1)) 而不是调用 strlen()。strlen() 对数组长度一无所知;它只是在达到 '\0' 值的字符之前报告字节数。在您的平台上检查“man strlen”,或者,如果不可用,请在网络上搜索“man strlen”。实际上,我有点惊讶这并没有因为访问冲突而彻底崩溃。

[编辑:听听 R. Martinho Fernandes。您正在使用 C 约定和 C 标准库处理字符串。在 C++ 中有更好、更安全的方法来做这件事,除非你的导师告诉你不这样做。]

[编辑]:如果由于某种原因你知道你将传递一个未初始化的 char 数组给 strlen(),那么将第一个字节设置为 '\0' 就像另一张海报建议的那样会让 strlen() 开心。但是再看看你的代码,我真的怀疑 strlen() 是你想要在这里做的。我认为这会给你一个逻辑错误。有关循环条件,请参阅我上面的建议。

就初始化 C 风格零终止字符串的正确方法而言,您希望使用值为 '\0' 的 memset(),如

memset(St, '\0', StLen);

我相信原型在 string.h 中。这将减少您以后弄乱字符串完整性的方式,至少在您第一次写入时是这样。始终初始化内存是一个很好的常规做法,但对于以零结尾的字符串尤其重要。

如果您要对以零结尾的字符串做更多的工作,一个好的经验法则是“str”函数通常是不安全的,而“strn”函数在可用且可行时是首选。当然,“strn”函数通常更容易使用,因为您必须跟踪缓冲区大小。有关差异,请参见 strcpy() 和 strncpy() 或 strcat() 和 strncat() 的手册条目。但同样,我认为 strlen() 在这种情况下甚至不是你想要的。

于 2012-05-02T04:42:21.480 回答