so, code supposed scramble words of sentence without altering order appear on input. code works fine, @ end of output there's blank space leads presentation error.
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string line; while(getline(cin,line)){ stringstream ss(line); string word; while(ss>>word){ string sword; for(int i=word.length()-1;i>=0;i--) { sword+=word.at(i); } cout << sword << " "; } cout << endl; } }
that caused cout << sword << " ";
line prints blank space regardless of position of word. i've attempted rewrite part of code to:
cout << sword; if(ss>>word) cout << " "; // if there following word, print space; else don't
but since i'm writing ss>>word
again, when the next iteration begins, begins on 3rd word(or 5th, 7th,etc.) skipping not intend to.
is there simple way of achieving this?
thanks in advance!
you can use bool
test whether you're displaying first word or not, like:
bool is_first = true; // bool flag test whether first word or not while(ss>>word){ string sword; for(int i=word.length()-1;i>=0;i--) { sword+=word.at(i); } if(is_first){ // first word cout << sword; is_first = false; } else{ // not first word cout << " " << sword; } }
in way, print " " << sword;
@ each iteration, except on first iteration, don't output space.
Comments
Post a Comment