题目很好理解,但是自己写完提交后,最后一个测试点总是报段错误,一直找不到原因
思路
将每个单词压栈,最后再推出
代码如下(已AC),提交使用g++
#include<bits/stdc++.h>
using namespace std;
int main()
{
stack<string> s;
string word="", str;
/* 为什么这样提取单词会报段错误?而用下面while提取就不会?
getline(cin, str);
for(int i = 0; i < str.length(); i++)
{
if(isalpha(str[i])) //拼接单词
{
word += str[i];
}
else if(str[i]==' ')
{
if(word.length())
{
s.push(word);
word = "";
}
}
}
if(word.length()) //最后一个单词入栈
{
s.push(word);
word = "";
}
*/
//【上文所说while】
while(cin >> str)
s.push(str);
cout << s.top();
s.pop();
while(!s.empty())
{
cout << " "+s.top();
s.pop();
}
return 0;
}