程序读取包含内容的文本文件
A DPX
A QRT
在堆栈上推送DPX和QRT。但是在显示stack {void show()}时,它不显示stack [0]。不知道为什么!?它正被推到堆栈上。元素堆栈[0]在push()中显示但不在show()
中const int MAX = 10 ;
struct car
{
char * lPlate;
int moves;
};
class garage
{
private :
char * stack[MAX] ;
int top ;
public :
garage( )
{
top = -1 ;
}
void arrive(struct car c)
{
push(c.lPlate);
}
void depart(struct car c )
{
}
void push ( char * item ) ;
char* pop( ) ;
void show();
} ;
void garage:: push ( char* item )
{
if ( top == MAX - 1 )
cout << endl << "Sorry. Parking lot is full" ;
else
{
top++ ;
strcpy(stack[top] , item) ;
}
cout<<"In push: "<<stack[top];
}
char * garage:: pop( )
{
if ( top == -1 )
{
cout << endl << "Parking lot empty is empty" ;
return NULL ;
}
return stack[top--] ;
}
void garage:: show()
{
cout<<" \nParking Lot Status:\n";
if( top == -1 )
{
cout << endl << "Parking lot is empty" ;
return ;
}
int i=top;
cout<<"In show "<<stack[0]<<endl;
while(i>-1)
{
cout<<stack[i]<<endl; i--;
}
}
int main()
{
clrscr();
char *action;
garage g;
ifstream fin("TEST");
if(!fin){cout<<"Cannot open i/p file \n\n";return 1;}
char str1[80],str2[40]; int i,j;
while(!fin.eof())
{
fin.getline(str2,MAX);
struct car c;//create a car obj
char * pch;
pch = strtok (str2," ,.-");//split string on getting <space>/<,>/<.>/<->
while (pch != NULL)
{
action=pch;
pch = strtok (NULL, " ,.-");
c.lPlate=pch;
pch=NULL;
cout<<"\nAction: "<<action<<" lPlate: "<<c.lPlate<<"\n";
switch(*action)
{
case 'A':
g.arrive(c);
break;
case 'D':
g.depart(c);
break;
}
}
cout<<"\n\n";
}
fin.close();
cout<<"\n";
g.show();
getch();
}
答案 0 :(得分:0)
数组
char * stack[MAX] ;
未初始化。它是一个由10(MAX)指针组成的数组。每个指针都没有初始化。
在方法pop中,在将项目复制到堆栈之前,初始化&#34; top&#34;堆栈项目
top++ ;
int length = strlen(item)+1; //+1 for null terminating character
stack[top] = new char[length]; //allocate memory
strncpy(stack[top] , item, length); //prefer strncpy
阅读文件后
A DPX
A QRT
这将导致一个看起来像这样的数组
请注意
将pop方法更改为类似
的方法int length = strlen(stack[top])+1;
char *returnItem = new char[length];
strncpy(returnItem,stack[top],length);
delete stack[top];
top--;
return returnItem;
谁曾调用pop方法需要为#34; returnItem&#34;
释放内存在解构器中释放仍由堆栈数组保持的所有内存,即
~garage() {
for (int i=top; i>=0; i--) {
std::cout << "clean up" << i << std::endl;
delete stack[i];
}
}