PDA

View Full Version : Reading in string with spaces


Nickelxk5
07-02-2010, 05:10 PM
Hi guys, I was trying to make a program the allows a user to enter a string, and get every possible arrangement of those letters. I used the random_shuffle() function from algorithms to shuffle the letters around in my string array. then, i created a vector that holds all the random shuffled up strings. But before it enters the string into the vector, i created a function, indexof, to check the contents of the vector to confirm that word would not be repeated. The problem i am having is that the program will bug up when it reads in spaces. I have went through and manually set break points and i have seen that the variable holding my string has the space, but im unclear as to why it bugs up. I just need another eye thanks, here's all the code.

#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#include <vector>



using namespace std;

void pVector(vector<string> print);
int indexof(vector<string> vec, string word);
long int factorial(int n);

ofstream wFile;
ifstream rFile;



int main() {

wFile.open("scramble.txt");
rFile.open("scramble.txt");


vector<string> print;
string name;
getline (cin, name);
int long letters = name.length();
letters = factorial(letters);


while (print.size() < letters){
random_shuffle(name.begin(), name.end());


if( indexof(print, name) == -1){
print.push_back(name);
}
}
pVector(print);

wFile.close();
rFile.close();
system("pause");
}


void pVector(vector<string> print){

for (int i = 0; i < print.size(); i ++){
wFile << print.at(i) << endl;
}

}

int indexof(vector<string> vec, string word){

for (int i = 0; i < vec.size(); i++){
if(vec.at(i) == word)
return i;
}
return -1;
}
long int factorial(int num){
int result;

if (num <= 1) return 1;

result = num * factorial(num - 1);
return result;

}

oracleguy
07-02-2010, 05:26 PM
Where exactly in the code is the program malfunctioning? Like which function or if you even know the line where things go astray, that'd be good.

Nickelxk5
07-02-2010, 06:35 PM
so i went in and decided to add a cout command everytime there was a new word added to the vector. But it turns out when i use a space, it does scramble the text correctly, but it goes into an infinite loop.

its seems to be in this section of code:

while (print.size() < letters){
random_shuffle(name.begin(), name.end());


if( indexof(print, name) == -1){
print.push_back(name);
cout << name << " Entered Vector\n";
}
}

Nickelxk5
07-02-2010, 07:49 PM
Ok, well i figured it out, for one, i was not refrenceing my vector so when i got to extreme values it just slowed down, and also you have to make a quick function to remove any repeated letters or else it messe sit all up in an endless loop.