比如輸入
Hello World Here I Come
輸出
Come I Here World Hello
可見並不會告訴我們要輸入幾個字符串,必須找到一個終止條件讓輸入停止
利用cin並不會輸入空格可以將這些字符分開,以回車鍵結束,想到getchar()可以接受回車鍵(ASCII為32)
完整代碼如下
#include<iostream> using namespace std; int main() { int i=0; char k=32;//空格的ASCII碼是32 // cout<<"k="<<k; string s[1000],temp_s; while(k==32) { cin>>s[i]; i++; k = getchar(); } cout<<s[i-1]; for(int j=i-2;j>=0;j--) cout<<" "<<s[j]; return 0; }