My C++ problem

Discussion in 'Computer Science & Culture' started by curioucity, Oct 16, 2004.

Thread Status:
Not open for further replies.
  1. curioucity Unbelievable and odd Registered Senior Member

    Messages:
    2,429
    Hello everyone.

    Just like the title say, in less than a week, I am to submit a C++ assignment I haven't been able to work out well. This is the fourth, and I've screwed up the last three, but still, maybe getting a good fourth may help me get enough to pass (to tell you the truth, I've failed this subject 3 times with my own effort...).

    Okay, onto the problem:

    The assignment problem is to read an text file (.txt format) and store every word in the text in a data structure (this time a binary search tree), so example: there a text:
    "This is a text"
    From file "text.txt" (the actuall text file supposedly dosn't contain those quote marks). My plan is to read the file line by line, store each word in a node, then each node will have a pointer to the 'right' and pointer to the left', with the first word being the head, and then subsequent words are compared fo\irst to the head to be decided to be moved to right or left.. Then this is the class I plan:

    class document{
    public:
    void loadText(document*); //function for reading the text file
    void display(document*); //displaying the read text inj whatever manner deemed fit
    private:
    struct wordata{
    char* word; //for storing every word
    }
    wordata* W; //dynamic memory array
    wordata* head; //for head pointer
    wordata* left;
    wordata* right; //left or right subordinates
    }


    And I deicde to have these lines in the main function:


    main(){
    document D;
    ..........
    loadText(&D); //in other words, I intended to use this as parameter
    .......
    }


    Here are my problems:
    1) There is no consutructor/destructor in my tree, and I'm always stuck when trying to make em.
    2) I always get an error when I'm reading the text file to the program in whatever way I know, even after I asked for some people's help. Here are some methods that had failed me:
    A--reading line by line, with every line stored in a buffer string, then read the buffer string character by character, with every space as an increment/movement trigger.
    B--Reading word by word right away.

    I hope I can get help here. Sure, this doesn't seem to matter in the end, but the last good mark may convince my teacher to stop giving me F each semester...

    Thanks.
     
    Last edited: Oct 16, 2004
  2. Google AdSense Guest Advertisement



    to hide all adverts.
  3. Blindman Valued Senior Member

    Messages:
    1,425
    This may help.. Didnt have anything beter to do while waiting to for a freind to turn up so there you go.
    I have not compiled it so use it as an example as it may have a few syntax errors.

    Code:
    // reads a file and then write a file of the words forward and then back. Then cleans up and exits.
    #define WORDFILE "words.txt"			// input file
    #define WORDFORWARDFILE "wordForward.txt"		// output
    #define WORDBACKWARDFILE "wordBackward.txt"	//output
    
    
    //********************************************************************************************************************
    class words  // class to contain a word
    {
    public:
    	char *word;  		 // pointer to a word string
    	words *next;		 // pointer to the next word
    	words *previous; 	// pointer to the previous word
    	words(char *word); 	// constructor
    	~words();
    };
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    words::words(char *w) 			 // construct
    {
    	word = new char[strlen(w)+1]; 	// create a array for the string include space for the 0 to terminate the string
    	strcpy(word,w);			// copy the new word into the new array;
    	next = NULL; 			// set the pointers to the next and prev to NULL;
    	prev = NULL;
    }
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    words::~words()					 // destruct
    {
    	delete [] word;				 // delete the word
    	if(next != NULL) next->prev = NULL;	 // remove any pointers to this word
    	if(prev != NULL) prev->next =NULL;
    }
    //********************************************************************************************************************
    #define MAXWORDLENGTH 100  		// length of biggest word.
    class WordReadWrite				// class to read and write words
    {
    public:
    	FILE *fp;				// file pointer
    	char  word[MAXWORDLENGTH];		// space for a word. This will create a buffer overflow because I dont check for the word length befor reading the word,
    	bool noMoreWords;			// the end of file has been reached
    	WordReadWrite(char *filename,bool read);		// open the file
    	~WordReadWrite();				// destruct and close file;
    	char * GetNextWord();			// read the next word from the file
    	WriteWord(char *word);			// write a word to a file
    };
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    WordReadWrite::WordReadWrite(char *filename,bool read)
    {
    	if(read)	fp = fopen(filename,"rt"); 		// open the file for reading
    	else fp = fopen(filename,"wt");                // open file for writing
    	if(fp == NULL) 			// if the is an error
    	{
    		noMoreWords = true;  	// there are no more words
    		return;  
    	}
    	noMoreWord = false; 		 // ok there may be more words
    }
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    WordReadWrite::~WordReadWrite()
    {
    	if(fp!=NULL) fclose(fp);  		// if the file is open close it
    }
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    char * WordReadWrite::GetNextWord()
    {
    	if(eof(fp))			// if the file is ant the end
    	{
    		 noMoreWords = true;  
    		return NULL;		// return a null for word
    	}
    
    	fscanf(fp,"%s",word); 		// read the next word from file
    	return(word);			 // return the word
    }
    WordReadWrite::WriteWord(char *word)
    {
    	fprintf(fp,"%s ",word); 		//write the word and a space
    }
    //********************************************************************************************************************
    
    main()
    {
    	//-------------------------------------------------------------------------------------------
    	// create pointers and open file
    	//-------------------------------------------------------------------------------------------
    	words *firstWord;
    	words *lastWord;
    	words *currentWord;
    	word *prevWord;
    	firstWord == NULL;
    	WordReadWrite *wordRead = new WordReadWrite(WORDFILE,true); 	 // open the file
    
    	//-------------------------------------------------------------------------------------------
    	// read each word from the file and add it to the list
    	//-------------------------------------------------------------------------------------------
    	*word = wordRead->GetNextWord(&noMoreWords);		// get the first word
    	while( !wordRead->noMoreWords)				// if there is a word add it
    	{
    		currentWord = new words(word);   			 // create a new word class
    		if(firstWord == NULL) firstWord = currentWord;  		 // if the first word point is not set the set it now
    		else    
    		{					
    			prevWord->next = currentWord; 			// link previous word to this new word
    			currentWord->prev = prevWord; 			// link this word to the previous
    		}
    		prevWord = currentWord; 				// store the location of the previous word
    		word = wordRead->GetNextWord(&noMoreWords); 		 // read the next word
    	}
    	delete wordRead;   						// no longer needed so close the file
    	if(firstWord == NULL) return;					// there are no words so exit now
    	lastWord = currentWord;						// point to the last word in the list.
    
    	//-------------------------------------------------------------------------------------------
    	// now display the words in forward order;
    	//-------------------------------------------------------------------------------------------
    	WordReadWrite *wordWrite = new WordReadWrite(WORDFORWARDFILE ,false); 	 // open the file
    	currentWord = firstWord;  							 // go to start of list
    	while(currentWord != NULL)
    	{
    		wordWrite->WriteWord(currentWord->word);  				// write the word the word
    		currentWord = currentWord->next; 					// move to the next word
    	}
    	delete wordWrite;								// close the file
    
    	//-------------------------------------------------------------------------------------------
    	// display the words in revers order
    	//-------------------------------------------------------------------------------------------
    	wordWrite = new WordReadWrite(WORDBACKWARDFILE,false); 
    	currentWord = lastWord;  					// go to endt of list
    	while(currentWord != NULL)
    	{
    		displayWord(currentWord->word);  			// display the word
    		currentWord = currentWord->prev; 			// move to the prev word
    	}
    	delete wordWrite;						// close the file
    
    	//-------------------------------------------------------------------------------------------
    	// now delete all words
    	//-------------------------------------------------------------------------------------------
    	currentWord = firstWord;  					//  get the first word
    	while(currentWord != NULL) 
    	{
    		words *tempWord = currentWord->next; 			// create a temp pointer to the next word
    		delete currentWord;					// delete the word
    		currentWord = tempWord;				// point to the next word;
    	}
    
    }
    
    EDIT
    I forgot to put the
    #include "stdio.h"
    Should be at the start of the code.
     
    Last edited: Oct 16, 2004
  4. Google AdSense Guest Advertisement



    to hide all adverts.
  5. curioucity Unbelievable and odd Registered Senior Member

    Messages:
    2,429
    Thank you. By the way, my computing lab is open only on weekdays so I can only start testing it on Monday. I'll let you know by then about any other rpoblem I'll get.
     
  6. Google AdSense Guest Advertisement



    to hide all adverts.
  7. Blindman Valued Senior Member

    Messages:
    1,425
    Fixed it for you. This will work. Removed all syntax errors and added two new lines to creat and delete the temp word string in main.

    This copy will compile on almost all standard C++ compilers.
    the includes should be stdio.h and string.h wra
    Code:
    // reads a file and then write a file of the words forward and then back. Then cleans up and exits.
    #define WORDFILE "data.txt"			// input file
    #define WORDFORWARDFILE "wordForward.txt"		// output
    #define WORDBACKWARDFILE "wordBackward.txt"	//output
    
    #include "stdio.h"
    #include "string.h"
    //**************************************************  **************************************************  ****************
    class words  // class to contain a word
    {
    public:
    	char *word;  		 // pointer to a word string
    	words *next;		 // pointer to the next word
    	words *prev; 	// pointer to the previous word
    	words(char *word); 	// constructor
    	~words();
    };
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    words::words(char *w) 			 // construct
    {
    	word = new char[strlen(w)+1]; 	// create a array for the string include space for the 0 to terminate the string
    	strcpy(word,w);			// copy the new word into the new array;
    	next = NULL; 			// set the pointers to the next and prev to NULL;
    	prev = NULL;
    }
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    words::~words()					 // destruct
    {
    	delete [] word;				 // delete the word
    	if(next != NULL) next->prev = NULL;	 // remove any pointers to this word
    	if(prev != NULL) prev->next =NULL;
    }
    //**************************************************  **************************************************  ****************
    #define MAXWORDLENGTH 100  		// length of biggest word.
    class WordReadWrite				// class to read and write words
    {
    public:
    	FILE *fp;				// file pointer
    	char  word[MAXWORDLENGTH];		// space for a word. This will create a buffer overflow because I dont check for the word length befor reading the word,
    	bool noMoreWords;			// the end of file has been reached
    	WordReadWrite(char *filename,bool read);		// open the file
    	~WordReadWrite();				// destruct and close file;
    	char * GetNextWord();			// read the next word from the file
    	void WriteWord(char *word);			// write a word to a file
    };
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    WordReadWrite::WordReadWrite(char *filename,bool read)
    {
    	if(read)	fp = fopen(filename,"rt"); 		// open the file for reading
    	else fp = fopen(filename,"wt");                // open file for writing
    	if(fp == NULL) 			// if the is an error
    	{
    		noMoreWords = true;  	// there are no more words
    		return;  
    	}
    	noMoreWords = false; 		 // ok there may be more words
    }
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    WordReadWrite::~WordReadWrite()
    {
    	if(fp!=NULL) fclose(fp);  		// if the file is open close it
    }
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    char * WordReadWrite::GetNextWord()
    {
    	if(feof(fp))			// if the file is ant the end
    	{
    		 noMoreWords = true;  
    		return NULL;		// return a null for word
    	}
    
    	fscanf(fp,"%s",word); 		// read the next word from file
    	return(word);			 // return the word
    }
    void WordReadWrite::WriteWord(char *word)
    {
    	fprintf(fp,"%s ",word); 		//write the word and a space
    }
    //**************************************************  **************************************************  ****************
    
    main(void)
    {
    	//-------------------------------------------------------------------------------------------
    	// create pointers and open file
    	//-------------------------------------------------------------------------------------------
    	
    	words *firstWord;
    	words *lastWord;
    	words *currentWord;
    	words *prevWord;
    	firstWord = NULL;
    	char *word = new char[MAXWORDLENGTH];
    	
    	WordReadWrite *wordRead = new WordReadWrite(WORDFILE,true); 	 // open the file
    	printf("start");
    	//-------------------------------------------------------------------------------------------
    	// read each word from the file and add it to the list
    	//-------------------------------------------------------------------------------------------
    	word = wordRead->GetNextWord();		// get the first word
    	while( !wordRead->noMoreWords)				// if there is a word add it
    	{
    		currentWord = new words(word);   			 // create a new word class
    		if(firstWord == NULL) firstWord = currentWord;  		 // if the first word point is not set the set it now
    		else    
    		{					
    			prevWord->next = currentWord; 			// link previous word to this new word
    			currentWord->prev = prevWord; 			// link this word to the previous
    		}
    		prevWord = currentWord; 				// store the location of the previous word
    		word = wordRead->GetNextWord(); 		 // read the next word
    	}
    	delete wordRead;   						// no longer needed so close the file
    	if(firstWord == NULL) return(true);					// there are no words so exit now
    	lastWord = currentWord;						// point to the last word in the list.
    
    	//-------------------------------------------------------------------------------------------
    	// now display the words in forward order;
    	//-------------------------------------------------------------------------------------------
    	WordReadWrite *wordWrite = new WordReadWrite(WORDFORWARDFILE ,false); 	 // open the file
    	currentWord = firstWord;  							 // go to start of list
    	while(currentWord != NULL)
    	{
    		wordWrite->WriteWord(currentWord->word);  				// write the word the word
    		currentWord = currentWord->next; 					// move to the next word
    	}
    	delete wordWrite;								// close the file
    
    	//-------------------------------------------------------------------------------------------
    	// display the words in revers order
    	//-------------------------------------------------------------------------------------------
    	wordWrite = new WordReadWrite(WORDBACKWARDFILE,false); 
    	currentWord = lastWord;  					// go to endt of list
    	while(currentWord != NULL)
    	{
    		wordWrite->WriteWord(currentWord->word);  			// display the word
    		currentWord = currentWord->prev; 			// move to the prev word
    	}
    	delete wordWrite;						// close the file
    
    	//-------------------------------------------------------------------------------------------
    	// now delete all words
    	//-------------------------------------------------------------------------------------------
    	currentWord = firstWord;  					//  get the first word
    	while(currentWord != NULL) 
    	{
    		words *tempWord = currentWord->next; 			// create a temp pointer to the next word
    		delete currentWord;					// delete the word
    		currentWord = tempWord;				// point to the next word;
    	}
    	delete []word;
    
    }
    
     
    Last edited: Oct 16, 2004
  8. Blindman Valued Senior Member

    Messages:
    1,425
    The return will take care of the missing else. But you could do it by removing the return and adding an else.
     
  9. Blindman Valued Senior Member

    Messages:
    1,425
    The main linked list of words is dynamic memory. The code creates memory for each word as they are added to the list. I have to delete the words at the end of the code.

    The static var word in wordReadWrite is allocate the same way as a dynamic array, you just don't have to write the extra code.

    You must have a balance between static an dynamic memory usage. Especially if you are fequently creating and deleting objects. it can lead to memory fragmentation and reduced performance.
     
  10. curioucity Unbelievable and odd Registered Senior Member

    Messages:
    2,429
    EDIT: DON'T blame Blindman for triple posting... I accidentally deleted my post somewhere in between his.


    Hi again....
    It seems that my habit of not doing everything well is getting into me..... I forgot to mention some of the things that have to be taken into account for this assignment, sorry about that.... I think I'll quote my lab test problem right away so that in the future, no more silly problem will present

    As you can see, I missed the point that I must read the text file line by line (and the lines may or may not be ended by a return/new line code), and that every word has to be given an extra parameter: its location.

    I'm sorry if I wasted your time, but I still thank you for your helps.
     
  11. cato less hate, more science Registered Senior Member

    Messages:
    2,959
    I have an easy problem for you all (because I just started taking a c/c++ class)
    I need to know (by noon tomorrow if possible) how to reject an input in "c". I know how to exclude a range of values ( x < a || x > b) but I need to know how to exclude three values and leave the rest. i.e. I need to exclude the numbers 1, 3, and 4.

    any help would be gravy
     
  12. Stryder Keeper of "good" ideas. Valued Senior Member

    Messages:
    13,105
    There are multiple ways of doing that, for instance the usage of && (And)
    (a && b && d)

    Or there is the "if" method with each "rule" written singularly (only good in hardcoding, because it's useless dynamically. In fact it's one to avoid.)

    Then there is the potential to use a "while" loop with a "case" statement.

    Take your pick.
     
  13. cato less hate, more science Registered Senior Member

    Messages:
    2,959
    ohh, I am sorry, I should have specified. It must be done within a "do...while" statement
     
  14. StrayDogStrut Registered Member

    Messages:
    23
    I may be misunderstanding what your saying, but it sounds as if you want to accept anything and then break out if it's something invalid. If that's right, here's your solution (this is just the main)

    {
    String accepted = "";
    String proposed = "";
    do{
    cin>>proposed;
    if (proposed != "1" && proposed != "3" && proposed != "4")
    accepted += proposed;
    }while (proposed != "1" && proposed != "3" && proposed != "4");
    cout<<accepted;
    }

    The reason I wasn't sure if this is what you're looking for is because the do while is rather pointless there. Also, I haven't done C++ in awhile, so I don't remember if you need .equals() for strings or what. Anyway, hope this helps, sorry if it's useless
     
  15. cato less hate, more science Registered Senior Member

    Messages:
    2,959
    that sort of helped. thanks, I will just get it from someone before class.
     
Thread Status:
Not open for further replies.

Share This Page