hello all, I have this function which is posted below, and the second time the while loop goes through it crashes. On MSVC++ it terminates the dos window, and on unix I get a floating exeption error.
I've pin pointed the problem to be where I get the second random number...near the buttom of the function...any ideas??
axon
Code:
void readInFileAndGetChars(string fileName, char text[], int& sum)
{
//declaring variables
int i;
ifstream inStream;
inStream.open(fileName.c_str()); //open user chosen file
if ( inStream.fail() ) { //check if file opened right
cout << "Input file opening for " << fileName << " failed. Exiting...\n\n";
exit(-1);
}
for ( i=0; i<MAX_SIZE; i++ ){ //input file into the array
inStream.get(text[i]);
}
cout << endl << endl << fileName << " consists of " << MAX_SIZE << " characters.\n\n "
<< endl;
}
//=============================================
void generateOutput(char text[], int window, int length, int sum)
{
//declaring arrays
char *windowArr = new char[window]; //window array
int allChars[127];
//declaring variables
int randomPosition = (rand()/2);//( rand()%MAX_SIZE ); //get random number
bool notDone = true;
int i, j, temp;
int count2 = 0; //couter for how many times through loop
while(notDone)
{
int randChar=0;
int count = 0; //counter for comparison part
int sum2 = 0; //sum for all characters that follow window
char printChar; //randomly chosen charcter that will follow window
for( i=0; i<window; i++){ //match random position characters with window
if(count2 == 0){
windowArr[i] = text[randomPosition + i];
}else{
windowArr[i] = windowArr[i+1];
windowArr[window-1] = printChar;
}
}
for( i=0; i<127; i++){ //set every element to 0
allChars[i] = 0;
}
for( i=0; i<MAX_SIZE; i++){ //COMPARISON
count = 1;
if( windowArr[0] == text[i] ){
for( j=1; j<window; j++ ){
if( windowArr[j] == text[i+j] ){
count++;
}else{ break;}
if( count == window ){
allChars[ text[j+i+1]]++; //to get next char and add 1 to it
break;
}else{continue;}
}
}
}
for(i=0; i<127; i++){ //get sum of characters which appear at least 1 time
if(allChars[i] > 0){
sum2 += allChars[i];
}
}
char *lastChar = new char[sum2]; //declare array to hold characters that appear after window
temp = sum2;
for( i=0; i<127; i++){ //put all characters that appear at least once
if( allChars[i] > 0 ){ //into an array
while( temp != -1 ){
for( j=1; j<=allChars[i]; j++){
lastChar[i-i+temp-j] = (char)i;
}
temp = temp - (1*allChars[i]);
break;
}
}
}
/****The PROBLEM IS IN THE LINE BELOW***/
randChar = (rand()%sum2); //get random position for next char
printChar = lastChar[randChar];
cout.flush() << printChar;
count2++;
if( count2 == length ){
notDone = false;
}
}
}