【题目要求】输入若干串字符,每次遇到换行符’\n’时,则输出本行当前处理结果。输入时以“#”字符作为结束符,当遇到这个符号后,意味着字符串输入结束。 在输入过程中如果输入“<”,则表示回退一格;在输入过程中如果包含了“@”,则表示回退到本行行首。
【提示】 (1)这道题目利用定义的Stack类实现。输入字符时不要采用cin>>ch;的方式接收字符串,因为cin会屏蔽换行符,不能达到预期的效果。可以考虑采用ch=getchar();或cin.get();语句接收字符。在处理字符串时,要分别对’<’,’@’,’#’,’\n’进行不同的处理。 (2)可以在Stack类中增加两个成员函数,方便调用和显示: void displayFromBottom();//从栈底到栈顶显示栈中的元素。
#include <iostream>
using namespace std;
class Stack {
private:
int size;
char* stackArray;
int top;
public:
Stack(int s) {
size = s;
stackArray = new char[size];
top = -1;
}
void push(char c) {
stackArray[++top] = c;
}
void pop() {
if (isEmpty()) {
cout<<"堆栈为空,无法弹出"<<endl;
}
else{
top--;
}
}
char topElement() {
if (isEmpty()) {
throw "堆栈为空。";
}
return stackArray[top];
}
bool isEmpty() {
if(top>-1)
return false;
else
return true;
}
void displayFromBottom() {
if(!isEmpty()){
for (int i = 0; i <= top; i++) {
cout << stackArray[i];
}
cout << endl;
}
else
cout<<"栈为空"<<endl;
}
void setNull() {
top=-1;
}
};
int main() {
int stackSize;
cout << "输入栈的大小:";
cin >> stackSize;
Stack myStack(stackSize);
getchar();//清除换行符
cout << "输入待处理的字符串(输入<代表退一格,输入@代表清除到行首,输入#结束):"<<endl;
char ch;
while ((ch = getchar()) != '#') {
if(ch=='<'||ch=='@'||ch=='\n')
{
if (ch == '<') {
myStack.pop();
}
if (ch == '@') {
myStack.setNull();
}
if (ch == '\n') {
myStack.displayFromBottom();
myStack.setNull();
}
}
else {
myStack.push(ch);
}
}
myStack.displayFromBottom();
return 0;
}