This version is working. I've made //
comments throughout my code to better illustrate what I am having trouble with. The program is dependent on reading a text file. In the format of paragraphs with punctuation included.
One could copy this and the above into a text file and run the program.
// Word.cpp
#define _CRT_SECURE_NO_WARNINGS // disable warnings for strcpy
#define ARRY_SZ 100
#include <iostream>
#include <fstream>
#include "Word.h"
using namespace std;
Word::Word( const char* word )
{
ptr_ = new char[ strlen( word ) + 1 ];
strcpy( ptr_, word );
len_ = strlen( ptr_ );
}
Word::Word( const Word* theObject )
{
ptr_ = theObject->ptr_;
len_ = theObject->len_;
}
Word::~Word()
{
delete [] ptr_;
ptr_ = NULL;
}
char Word::GetFirstLetterLower()
{
// I want to use ptr_ and len_ here
// but the information is gone!
char c = 0;
return c;
}
char* Word::GetWord()
{
for (int x = 0; x < strlen( (char*)ptr_ ); x++)
ptr_[x]; // Results in a crash.
return ptr_;
}
// Word.h
const int FILE_PATH_SZ = 512;
class Word
{
private:
char* ptr_;
int len_;
public:
Word( const Word* ); // an appropriate default constructor
Word( const char* );
~Word( );
char GetFirstLetterLower( );
char* GetWord( );
static char fileEntry[ FILE_PATH_SZ ];
};
// main.cpp
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <iostream>
#include <fstream>
#include <string>
#endif
#include "Word.h"
using namespace std;
const int WORD_SZ = 100;
Word** g_wordArray;
int g_arrSz;
static char filePath[ FILE_PATH_SZ ] = {};
void FreeWordArray();
int main( const int argc, const char **argv )
{
int wrdCount = 0;
char usrMenuOption = 0,
getFirstLetter = 0,
tmpArray[WORD_SZ] = {},
*getWord = 0;
string str,
str2;
ifstream inFile,
inFile2;
do
{
cout << "Please make a selection: \n\
a) Read a text file\n\
b) Remove words starting with letter\n\
c) Print words to console\n\
d) Quit\n";
cin >> usrMenuOption;
switch( usrMenuOption )
{
case'A':
case'a':
cout << "Enter a file name: ";
cin.sync();
cin >> filePath;
inFile.open( filePath );
if ( !inFile ) return -1;
inFile >> str; // prime the eof flag
while ( !inFile.eof() )
{
inFile >> str;
wrdCount++;
g_wordArray = new Word *[wrdCount];
}
inFile.close();
inFile2.open( filePath );
while( !inFile2.eof() )
{
inFile2 >> str2;
for ( unsigned x = 0; x < str2.length(); x++ )
g_wordArray[x] = new Word( str2.c_str() );
}
cout << wrdCount << " Words read from the file " << endl;
inFile2.close();
break;
case'B':
case'b':
getFirstLetter = g_wordArray[wrdCount]->GetFirstLetterLower();
//getWord = g_wordArray[wrdCount]->GetWord();
cout << getWord << endl;
break;
case'C':
case'c':
break;
case'D':
case'd':
cout << "Quit Requested. " << endl;
break;
default:
cout << '"' << usrMenuOption << '"' << " Not Defined! " << endl;
}
} while (usrMenuOption != 'D' && usrMenuOption != 'd');
#ifdef _DEBUG
_CrtDumpMemoryLeaks();
#endif
cin.ignore();
return 0;
}
void FreeWordArray()
{
// free the memory that is allocated
return;
}