問題描述:
給定一句英語送巡,要求你編寫程序,將句中所有單詞的順序顛倒輸出。
輸入格式:
測試輸入包含一個測試用例彤侍,在一行內(nèi)給出總長度不超過 80 的字符串。字符串由若干單詞和若干空格組成逆趋,其中單詞是由英文字母(大小寫有區(qū)分)組成的字符串盏阶,單詞之間用 1 個空格分開,輸入保證句子末尾沒有多余的空格闻书。
輸出格式:
每個測試用例的輸出占一行名斟,輸出倒序后的句子。
輸入樣例:
Hello World Here I Come
輸出樣例:
Come I Here World Hello
思路:題目沒有給出輸入的字符串的個數(shù)魄眉,所以不能用以往的for循環(huán)來錄入砰盐。所以我們用while循環(huán)來錄入輸入樣例,根據(jù)用戶有沒有按下回車來作為循環(huán)中止的條件坑律⊙沂幔回車鍵用字符'\n'表示。根據(jù)輸入輸出可以發(fā)現(xiàn)這恰巧像先進(jìn)后出的棧一樣脾歇,所以可以考慮用棧來實現(xiàn)蒋腮。
實現(xiàn)如下:
#include <iostream>
#include <stack>
using namespace std;
int main()
{
char c; //接受空格,回車這些字符藕各,用來作為while循環(huán)的中止條件
string str;
stack<string>obj;
do
{
cin >> str;
obj.push(str);
} while ((c = getchar()) != '\n'); //getchar函數(shù)可以接受用戶錄入的一個字符
while (obj.size())
{
cout << obj.top();
if (obj.size() != 1)
{
cout << " ";
}
obj.pop();
}
cout << endl;
return 0;
}
當(dāng)然了池摧,這里用動態(tài)數(shù)組vector來實現(xiàn)說反話也是可以的。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string str;
vector<string>vec;
char c;
do
{
cin >> str;
vec.push_back(str);
} while ((c = getchar()) != '\n');
for (int i = vec.size() - 1 ; i >= 0 ; i--)
{
cout << vec[i];
if (i != 0)
{
cout << " ";
}
}
cout << endl;
return 0;
}