Originally Posted by
phantomotap
O_o
Are the names supposed to stay reversed?
Yes, in fact I was working on a generalized solution regardless of whitespace formatting and number of words entered.
Originally Posted by
phantomotap
Anyway, you have a bug related to not fully reversing the last word.
Soma
Good catch, thanks. I forgot a line of code for the last word. Here is the updated solution. Still doesn't feel "right" to me. I do understand this is one of those "why would you do it" type of questions but it is more of a brainteaser kind of thing. Any additional comments, as always, are appreciated.
Code:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
int main(){
//Preserve whitespace formatting
std::cin >> std::noskipws;
//grab entire input buffer and store in vector
std::istream_iterator<char>start(std::cin);
std::istream_iterator<char>eos;
std::vector<char>input(start,eos);
//reverse vector
std::reverse(input.begin(),input.end());
//reverse "words"
std::vector<char>::iterator wordstart=input.begin()+1,spacepos=input.begin()+1;
while(spacepos != input.end()){
if(*spacepos==' '&&(*(spacepos-1)!=' ' || *(spacepos-1)!='\n')){
std::reverse(wordstart,spacepos);
wordstart = spacepos+1;
}
++spacepos;
}
//reverse last word
std::reverse(wordstart,spacepos);
//output reversed input
std::copy(input.begin(),input.end(),std::ostream_iterator<char>(std::cout));
return (0);
}