I know there are a lot of coders that hang around here, so I have a question.
I made a pretty short program that reads an input file with text already in it, and produces an output file with all the internal letters of each word scrambled up (the theory is that your brain can still easily discern what each word is if the first and last letters are the same). It’s working fine, no compile errors or warnings, but it just stops reading around word 35 and the program sits there doing nothing until I force-close. Any ideas?
Program:
/* Matthew Shubert
7/02/2009
A program that scrambles the inner portion of words from a file
to show that the words are still readable by the human mind
*/
#include<iostream>
#include<cstdlib>
#include<string>
#include<algorithm>
#include<fstream>
using namespace std;
/*
This function takes an input word and scrambles the interior letters
by creating a substring and using the STL algorithm ‘random_shuffle’
*/
string scramble(string initial) {
if (initial.size() <= 3) // If the word is too short, don’t do anything
return initial;
string final;
string middle = initial.substr(1, initial.size()-2);
string compare = middle;
random_shuffle(middle.begin(), middle.end());
while (middle == compare)
random_shuffle(middle.begin(), middle.end()); // Ensures that the substring is actually changed
final = initial.at(0) + middle + initial.at(initial.size()-1);
return final;
}
int main() {
string word;
string s_word;
ifstream ifs;
ofstream ofs;
ifs.open("input_file.txt");
ofs.open("output_file.txt", ios::trunc);
int count = 1;
while (ifs >> word) {
s_word = scramble(word);
ofs << count << ' ' << s_word << endl; // numbers the lines and has one word per line
++count;
}
cout << "Task is complete
";
return 0;
}