/* Filename: wordgame.cpp * Author: Anthony Larrain * * Decription: This program will randomly pick a word, scramble the word * and output the scrambled word to the screen. The user * will then try to guess the word. * * Input file: music.dat -- this file will contain the names of musical instruments. The first line is an integer representing the number of words in the file. */ #include #include #include #include #include #include using namespace std; void scramble(char *word ); void swap(char &x, char &y); char** createList(int wordCount); void deleteList(char **wordList, int wordCount); const int WORD_LENGTH = 20; const char FILE_NAME [] = "music.dat"; int main() { ifstream fin(FILE_NAME); if(fin.fail()) { cerr << "Error opening music.dat" << endl; system("PAUSE"); exit(EXIT_FAILURE); } int wordCount; fin >> wordCount; char **wordList = createList(wordCount); for(int row = 0; row < wordCount; row++) { fin >> wordList[row]; } char response; char word[WORD_LENGTH],guess[WORD_LENGTH]; srand(time(NULL)); do{ int randWord = rand() % wordCount; strcpy(word,wordList[randWord]); scramble(word); cout << "Take a Guess\t" << word << endl; cin >> guess; if((strcmp(guess, wordList[randWord])) == 0){ cout << "Correct" << endl; }else{ cout <<"Incorrect, the word is " << wordList[randWord] << endl; } cout << "Another word (y)es ? "; cin >> response; }while(response == 'y' || response == 'Y'); deleteList(wordList,wordCount); system("PAUSE"); return 0; } void scramble(char *word) { int position; for(int i = 0; i < strlen(word); ++i){ swap(word[i], word[ rand() % strlen(word) ]); } } void swap(char &x, char &y) { char temp = x; x = y; y = temp; return; } char** createList(int wordCount){ // allocates the rows of wordList char **wordList = new char* [wordCount]; //for each row allocate the columns for(int i = 0; i < wordCount; i++){ wordList[i] = new char [WORD_LENGTH]; } return wordList; } void deleteList(char **wordList, int wordCount){ for(int i = 0; i < wordCount; i++){ delete [] wordList[i]; } delete [] wordList; }