Program only works sometimes...

Hello, this is my first post so here goes!
I am working on a program that scrambles the letters of each word of a sentence in the word is 4 or more letters. But, my instructor wants us to use his algorithm to only swap the second and third characters of each word.

Basically, when I input "I don't give a damn for a man that can only spell a word one way."
It is supposed to output "I d'not gvie a dman for a man taht can olny sepll a wrod one way"

Mine says: "I d'not gvie a madn for a man taht can lnoy epsll a rowd one way"

Here is my code:

#include <iostream>
using namespace std;

string scramble(string word) {

int r1;
int r2;
int placeholder;
string scramble;

while (cin >> word) {

if (word.length() > 3) {
r1 = rand() % (word.length() - 1);
r2 = r1;

while ( r2 == r1 ) {
r2 = rand() % (word.length() - 1);
}

placeholder = word[r1];
word[r1] = word[r2];
word[r2] = placeholder;
}
scramble = scramble + word + " ";
}
return scramble;
}

int main () {
cout << "Enter a phrase followed by the Enter key and Ctrl-Z/D. : "
<< endl;
string word;
cout << scramble(word) << endl;
return 0;
}


Any help at all would be greatly appreciated, thank you !
Could you put it in code tags...it makes it 1000 times easier to read.

Another thing, when I try to compile your code, it doesn't do anything. Once I've included string because I assume you are using code::blocks and have std::string automatically included, it still doesn't work...I get black screen :\

For a start, you aren't even inputting word. Shouldn't you get the whole line and put it into a string, find the spaces, sort it into words and then go from there?

Thanks
Last edited on
Oops when I entered it in I was just using spaces, I will try again.

Code:

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
string scramble(string word) {

    int r1;
    int r2;
    int placeholder;
    string scramble;

    while (cin >> word) {

        if (word.length() > 3) {
            r1 = rand() % (word.length() - 1);
            r2 = r1;

            while ( r2 == r1 ) {
                 r2 = rand() % (word.length() - 1);
            } 

        placeholder = word[r1];
        word[r1] = word[r2];
        word[r2] = placeholder;
        }
     scramble = scramble + word + " ";
     }
    return scramble;
}

int main () {
    cout << "Enter a phrase followed by the Enter key and Ctrl-Z/D. : "
    << endl;
    string word;
    cout << scramble(word) << endl;
    return 0;
}
The second part of your message scares me...

I have done it using a cin>> word; statement and done it without,
apparently, the cin >> word test in the while statement prompts me for my word automatically

It definitely intakes a string from me, and sorts them word by word. I am now thoroughly confused.

I use texteditor and my terminal on my mac to run it. I am pretty sure I am using the g++ compiler
Topic archived. No new replies allowed.