题目描述
给定一句英语,要求编写程序,将句中所有单词按颠倒顺序输出。
输入格式:
测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。
字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,
单词之间用1个空格分开,输入保证句子末尾没有多余的空格。
输出格式:
每个测试用例的输出占一行,输出倒序后的句子
测试样例:
输入:Hello World Here I Come
输出:Come I Here World Hello
解题思路:
使用库函数strtok实现对字符串的分割
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main() {
stack<string> s;
string str;
getline(cin,str);
char* ch = (char *)str.c_str();//字符串转换为数组
const char* sep = " ";
char* buf;
char* word = strtok_s(ch,sep,&buf);//字符串分割
//strtok为线程不安全的函数
//strtok_s为线程安全的函数
while (word)
{
s.push(word);
word = strtok_s(NULL, sep,&buf);
}
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
system("pause");
return 0;
}