Help with my code

I am having trouble in printing jumbled words for an input word. There is something really silly thing in my program I am missing. Can someone eyeball this and tell me what could be wrong in this code? Your help is much appreciated.

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 "iostream"
#include "stdlib.h"
#include "string"
#include "vector"
#include "algorithm"
using namespace std;

vector<string> printJumbleWords(std::string str1){
	int length = str1.length();
	cout << "Length is" << length << " " << str1.length() << endl;
	int n,j;
	std::string temp = "";
	vector<int> indexCompleted;
	vector<string> output;
	for (int i = 0; i < length; i++){
		j = 0;
		temp.clear();
		indexCompleted.clear();
		temp[j++] = str1[i];
		indexCompleted.push_back(i);
		while (j < length){
            n = rand() % length;
			if (find(indexCompleted.begin(), indexCompleted.end(), n) == indexCompleted.end()){
				indexCompleted.push_back(n);
				temp[j++] = str1[n];
			}
		}
		temp[j] = '\0';
		cout << "temp is: " << temp << endl;
		output.push_back(temp);
	}
	return output;
}
int main(){
	std::string inStr;
	cout << "Enter the string" << endl;
	getline(cin, inStr);
	vector<string> out = printJumbleWords(inStr);
	for (auto i : out){
		cout << i << endl;
	}
	getchar();
   return 0;
}


This is the output I am seeing:

Enter the string
hello
Length is5 5
temp is:
temp is:
temp is:
temp is:
temp is:

Line 17: temp.length() == 0
Line 19: Access to temp[temp.length()], which shall not be modified.
Line 25: Access to temp[X], where X > temp.length(), is undefined behaviour.
Last edited on
Topic archived. No new replies allowed.