The idea is to get a sentence of words and then scramble the middle letters of each word without altering the position of the word in the sentance. So for example, the user inputs: Programming is very interesting! the output should be: Pogrmarmnig is vrey itenrseitng! So far, i have been able to write a program that scrambles the letters of only 1 word and would like to see if someone would be friendly enough to help me get an idea of what i can do to modify a string of words. Here is my code:
#include <iostream>
#include <cstring>
using namespace std;
string switcharoo(string s){
int frst = 1;
int lst = s.size()-1;
for (int i = frst; i < lst; i++){
srand (time(NULL));
int j= 1+rand() % lst;
char t = s[i];
s[i] = s[j];
s[j] = t;
}
return s;
}
int main(){
string stmt;
cout << "type a sentance: ";
getline(cin, stmt);
stmt = switcharoo(stmt);
cout << stmt;
You should use a while loop. Something along the lines of this:
1 2 3 4 5 6 7 8
string word;
while((cin >> word) && string(".!?").find(word[word.size()-1]) == string::npos)
{//while we could read in a word and it wasn't the last word
scramble(word);
cout << word;
}//now for the last word:
scramble(word.substr(0, word.size()-1);
cout << word;
#include <sstream>
#include <algorithm>
#include <iostream>
#include <string>
usingnamespace std;
string switcharoo(string s)
{
// in will be a cin-like object. Extracting input from it will
// return whatever is in s.
istringstream in(s) ;
string result ;
string token ;
while ( in >> token )
{
// no point in mixing up words of 3 letters or less.
// &token[1] is the address of the 2nd character in token.
// &token[token.length()-1] is the address of the last
// character in token.
// Like most ranges taken by std:: containers and alogrithms,
// it operates on first element to one in front of the last
// element pointed to.
if (token.length() > 3)
random_shuffle( &token[1], &token[token.length()-1]) ;
result += token ;
result += ' ' ;
}
return result ;
}
int main(){
string stmt;
cout << "type a sentence: ";
getline(cin, stmt);
stmt = switcharoo(stmt);
cout << stmt;
return 0;
}