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

당신은 (auto를위한 C++ 11)과 같이 사용할 수 있습니다 : (http://ideone.com/mxOCM1)

깨끗한 쉬운 솔루션은 표준 libraray에 의존하는 것입니다
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

:

// 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

a를 원래 입력 줄의 끝에 도달하면 공백이 생깁니다.

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

Put for 루프를 벗어나고 자하는 것은 당신에게 어떤 프로그래밍 미인 대회에서 우승하지 않을 것을

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

주 후 루프 내부에서이 코드.

+0

고마워요, 도와 주셔서 감사합니다 ... – user2957078