說反話(c++實現)


描述:給定一句英語,要求你編寫程序,將句中所有單詞的順序顛倒輸出。

輸入:測試輸入包含一個測試用例,在一行內給出總長度不超過80的字符串。字符串由若干單詞和若干空格組成,其中單詞是由英文字母(大小寫有區分)組成的字符串,單詞之間用1個空格分開,輸入保證句子末尾沒有多余的空格。

輸出:每個測試用例的輸出占一行,輸出倒序后的句子。

inout:Hello World Here I Come

output:Come I Here World Hello

就是要熟練使用string里的函數

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     string a, b,c;
 8     getline(cin, a);
 9     for (int i = 0; i < a.size(); i++)
10     {
11         if (a[i] == ' ')
12         {
13             c.push_back(' ');
14             b.insert(0, c);        //字符串插入函數
15             c.erase(0);            //刪除函數
16             continue;
17         }
18         c.push_back(a[i]);
19     }
20     c.push_back(' ');
21     b.insert(0, c);
22     b.erase(b.size() - 1);
23     cout << b << endl;
24     system("pause");
25     return 0;
26 }

還有一種方法是把每個單詞當成一個字符串,存在字符串數組了,逆序輸出

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     string a[100];
 8     int count = 0;
 9     do
10     {
11         cin >> a[count];
12         count++;
13     } while (getchar() != '\n');
14     for (int i = count - 1; i > 0; i--)
15         cout << a[i] << " ";
16     cout << a[0] << endl;
17     system("pause");
18     return 0;
19 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM