2014-05-24 54 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