Function that jumbles string

I have to write a function that takes a string as an input and displays a jumbled version of that string. I've asked user input for the string already in the main function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  void jumbleString (string& str)
{
    int x = str.length();//gets length of string
	for (int i = x; i>0; i--)
	{
		//randomly jumbles string
		int pos = rand()%x;
		char tmp = str[i-1];
		str[i-1] = str[pos];
		str[pos] = tmp;
	}

    
	return;
}


And then in the main function, I called the jumble function and tried to display the output. Here's part of the code of where I call the function.

1
2
3
4
5
	if (choice == '4')
		{
		  void jumbleString(string& str);
		  cout << &str << endl;
		}


The output I get for the jumbled string is: 0x7ffe0e90e6e0
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (choice == '4')
{
    // this is just the declaration of the function jumbleString
    void jumbleString(string& str);
    
    jumbleString(str) ; // this actually calls the function
    
    
    // this prints the address of the string str
    cout << &str << endl;
    
    // this prints the contents of the string str
    std::cout << str << '\n' ; 
}


Re. the implemenation of void jumbleString (string& str)
See: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Thank you! It works now.
Do you know how I could get it to not change the string and only display it?
Pass the string by value to the function (the function gets a copy of the string) and let it return the jumbled string.
std::string jumbleString( std::string str )

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <algorithm>
#include <random>

std::string jumbleString( std::string str )
{
     static std::mt19937 rng( std::random_device{}() ) ;
     std::shuffle( str.begin(), str.end(), rng ) ;
     return str ;
}

int main()
{
    const std::string str = "as an example, we will jumble this string." ;

    for( int i = 0 ; i < 5 ; ++i )
    {
        std::cout << "original: " << str << '\n' ;
        const std::string jumbled = jumbleString(str) ;
        std::cout << " jumbled: " << jumbled << "\n\n" ;
    }
}

http://coliru.stacked-crooked.com/a/19622ed0f2ec5a95
Topic archived. No new replies allowed.