【stack】为什么读取文件时候最后一个字符总是会读两遍?
代码:do
{
char tempChar;
sourceFile>>tempChar;
cout<<"读入的字符:"<<tempChar<<endl;
ElemType tElem;
tElem.changeElem(tempChar);
if((tempChar=='(')||(tempChar==')')||(tempChar=='{')||(tempChar=='}')||(tempChar=='[')||(tempChar==']'))
{
if(stack.isEmpty())
{
stack.push(tElem);
cout<<"isEmpty in"<<endl;/////////
continue;
}
if(isMatch(tempChar,stack.peek().getElem()))
{
stack.pop();
cout<<"out"<<endl;/////
}
else
{
stack.push(tElem);
cout<<"different in"<<endl;/////////
}
}
} while(!sourceFile.eof());
目的:判断文件中括号是否配对。
测试:
输入文件名:test.txt
读入的字符:(
isEmpty in
读入的字符:(
different in
读入的字符:(
different in
读入的字符:{
different in
读入的字符:}
out
读入的字符:[
different in
读入的字符:[
different in
读入的字符:[
different in
读入的字符:]
out
读入的字符:]
out
读入的字符:]
out
读入的字符:)
out
读入的字符:)
out
读入的字符:)
out
读入的字符:)
isEmpty in
0请按任意键继续. . .
test.txt文本内容:
((({}[[[]]])))
其他参考定义内容:
class Stack
{
public:
Stack(){top=0;}
~Stack(){}
void initStack(){top=0;}
void push(ElemType item)
{
if(top==MaxSize)
{
cout<<"栈溢出!"<<endl;
return;
}
top++;
elem[top]=item;
}
ElemType pop()
{
ElemType tempElem;
if(top==0)
{
cout<<"栈已空!"<<endl;
return tempElem;
}
tempElem=elem[top];
top--;
return tempElem;
}
ElemType peek(){return elem[top];}
bool isEmpty(){return !top;}
void ClearStack(){top=0;}
private:
int top;
ElemType elem[MaxSize+1];
};