【C++】用栈实现倒序输出一个字符串(可以带空格)

时间:2021-09-01 13:19:29

【C++】用栈实现倒序输出一个字符串(可以带空格)


思路:

1.用string和getline获取一行可以带空格的文本

2.将string转换为 char*

3.将char*入栈

4.将栈内元素出栈即可实现倒叙输出


/*获得一行文本,用栈倒序输出这行文本*/
#include <iostream>
#include <stack>//使用标准库里面的栈
#include <cstring>
#include <string>
using namespace std;
int main()
{
string temp;
getline(cin,temp);//获取一行可能包含有空格的文本
int len = temp.size();
const char *ss = temp.c_str();//将string转换成char*
stack <char> text;
int i = 0;
while(len--) {//入栈
text.push(ss[i++]);
}
while(!text.empty()){//出栈
cout << text.top();
text.pop();
}
return 0;
}

欢迎评论,欢迎交流。