思路:每输入一行字符串进栈st,把st复制一份到stShow,stShow循环4次输出栈顶元素后出栈,若空栈立即退出循环。
#include<stdio.h>
#include<stack>
#include<string>
using namespace std;
int main() {
//定义一个栈用来保存元素,一个栈用于输出元素
stack<string> st;
stack<string> stShow;
int m;
string str;
while (scanf("%d\n", &m) != EOF) {
char arr[100] = { 0 };
while (m--) {
scanf("%s", &arr);
str = arr;
st.push(str);//压栈保存
stShow = st;
for (int i = 0; i < 4; i++) {
if (stShow.empty())break;
printf("%d=%s ", i + 1, stShow.top().c_str());
stShow.pop();
}
printf("\n");
}
}
return 0;
}

京公网安备 11010502036488号