-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で、ヌルターミネータに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'作成できます。また、最初のインデックスに文字を書き込むことで、メモリをnullで終了する文字列に初期化できます。

于 2012-05-02T04:37:40.237 に答える
0

最初に思いつくのは、char 配列がゼロで終わる文字列であることが確実でない限り、strlen() を char 配列に使用できないということです。ループ条件では、strlen() を呼び出す代わりに (i < (StLen - 1)) をチェックする必要があります。strlen() は配列の長さについて何も知りません。'\0' 値の char に到達するまでのバイト数を報告するだけです。プラットフォームで「man strlen」を確認するか、それが利用できない場合は「man strlen」を Web 検索します。アクセス違反が原因でこれが完全にクラッシュしないことに、実際には少し驚いています。

[編集: 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 に答える