您的位置:首页 > 编程语言 > C语言/C++

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

2017-08-08 22:33 507 查看

【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;
}


欢迎评论,欢迎交流。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐