Need help with Word Scrambler Program

Feb 25, 2012 at 12:09am
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;

return 0;
}


Last edited on Feb 25, 2012 at 12:11am
Feb 25, 2012 at 12:19am
How about you cin one word at a time in a loop and scramble each word?
Feb 25, 2012 at 12:23am
Hi LB i am really new at C++. could you show me what type of loop would work to do this? (While or FOR)
Feb 27, 2012 at 5:30pm
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;
Feb 28, 2012 at 4:39pm
For kicks.. and to expose you to a few new ideas:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <sstream>
#include <algorithm>
#include <iostream>
#include <string>

using namespace 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;
}
Topic archived. No new replies allowed.