Hi, I have a program that can jumble one word while keeping the beginning and end characters. How do I do that to an entire sentence an entire sentence. For example, my program currently prints "Enter a word to jumble" I want it to be enter a sentence to jumble the words while keeping them in the same position? Would probably need an array or vector right?
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <string>
usingnamespace std;
template <typename iter_type>
void jumbleMiddle( iter_type begin, iter_type end )
{
if ( ++begin < --end )
random_shuffle(begin, end) ;
}
int main()
{
srand(time(0));
string sentence;
cout << "Enter a sentence to jumble \n";
std::getline(std::cin, sentence) ;
const std::string word_delims(" \n\t-\r\f.,'!@#$%^&*()_+{}|\\][=~`\":;?><") ;
std::string::iterator wordBeg = sentence.begin();
do{
// Ensure wordBeg is at the beginning of a word.
while ( wordBeg != sentence.end() && (word_delims.find(*wordBeg) != std::string::npos) )
++wordBeg ;
auto wordEnd = std::find_first_of(wordBeg, sentence.end(), word_delims.begin(), word_delims.end()) ;
if ( wordBeg != wordEnd )
{
jumbleMiddle(wordBeg,wordEnd) ;
wordBeg = wordEnd ;
}
} while ( wordBeg != sentence.end() ) ;
std::cout << sentence << '\n' ;
}
Some sample output:
Enter a sentence to jumble
Call me Ishmael. Some years ago--never mind how long precisely--having little or no money in my
purse, and nothing particular to interest me on shore, I thought I would sail about a little and see
the watery part of the world.
Call me Ihesmal. Smoe yreas ago--neevr mind how lnog pilcresey--havnig lttile or no menoy in my
purse, and nntohig pcutilarar to iserntet me on srhoe, I tguhhot I wuold sail auobt a lltite and see
the wertay prat of the wolrd.
[edit: Fix to avoid calling jumbleMiddle with two iterators to sentence.end(), which avoids incrementing said iterator to sentence.end() and causing undefined behavior.]