2014-05-24 52 views
-1

這裏就是我輸入的句子和向後打印程序...打印向後C++

#include<iostream> 
#include<string> 
using namespace std; 

int main(int argc, char* argv[]) { 
    string scrambleWords; 
    cout << "Please enter a sentence to scramble: "; 
    getline(cin, scrambleWords); 

    for (int print = scrambleWords.length() - 1; print >= 0; print--) 
    { 
     if (isspace(scrambleWords[print])) 
     { 
      for (unsigned int printIt = print + 1; 
         printIt < scrambleWords.length(); printIt++) 
      { 
       cout << scrambleWords[printIt]; 
       if (isspace(scrambleWords[printIt])) 
        break; 
      } 
     } 
    } 

    for (unsigned int gotIt = 0; gotIt < scrambleWords.length(); gotIt++) 
    { 
     cout << scrambleWords[gotIt]; 
     if (isspace(scrambleWords[gotIt])) 
      break; 
    } 
    cout << endl; 
} 

// OUTPUT 
// Please enter a sentence: birds and bees 
// beesand birds 
// Press any key to continue . . . 

正如你可以看到有一羣蜂之間沒有空格&鳥,所以我怎麼能添加空間在那裏?

+0

您可以打印每個單詞和後面的空格。蜜蜂沒有空間,所以沒有打印。 – broncoAbierto

回答

0

您可以使用類似(C++ 11 auto):(http://ideone.com/mxOCM1

void print_reverse(std::string s) 
{ 
    std::reverse(s.begin(), s.end()); 
    for (auto it = s.begin(); it != s.end();) { 
     auto it2 = std::find(it, s.end(), ' '); 
     std::reverse(it, it2); 
     it = it2; 
     if (it != s.end()) { 
      ++it; 
     } 
    } 
    std::cout << s << std::endl; 
} 
+0

有點高級,但我到了那裏,謝謝! – user2957078

1

最乾淨和最簡單的解決方法是依靠標準libraray:

// 1. Get your input string like you did 

// 2. Save the sentence as vector of words: 
stringstream sentence {scrambleWords}; 
vector<string> words; 
copy(istream_iterator<string>{sentence},istream_iterator<string>{}, 
    back_inserter(words)); 

// 3 a) Output the vector in reverse order 
for (auto i = words.rbegin(); i != words.rend(); ++i) 
    cout << *i << " "; 

// 3 b) or reverse the vector, then print it 
reverse(words.begin(),words.end()); 
for (const auto& x : words) 
    cout << x << " "; 
+0

有點高級,但我到了那裏,謝謝! – user2957078

+0

@ user2957078學習標準庫是一般的好建議。這對於每一位體面的C++程序員來說都是更加節省(更難以出錯),可能更快(聰明人努力優化它)並且易於閱讀和維護。當然,您可以節省寶貴的時間來開發和調試手工解決方案。 :) –

0

添加當您到達原始輸入行的末尾時,請輸入空格:

if printIt == scrambleWords.length()-1 
    cout << " "; 

Put這個代碼在內部for循環,後

if (isspace(scrambleWords[printIt])) 
    break; 

注意,對於環打破的出來是不會爲你贏得任何編程選美。

+0

謝謝,我感謝幫助... – user2957078