Jump to content


Loading A Text File To Array Of Strings


3 replies to this topic

#1 the_fifth_horseman

the_fifth_horseman

    Member Munchkin

  • Members
  • PipPipPip
  • 59 posts

Posted 27 August 2010 - 06:47 PM

I'm working on an engine for running various simple text-based adventures based on nodes with a limited range of options for the player to select from. (a working beta with a partially complete example module is attached)

Currently, I'm trying to clean up the code so that I can rewrite the event and link parsers into something more effective, but ran into some problems with a function supposed to load the contents of a text file into an array of strings.

What works:
- The number of lines is correctly counted and stored in the counter the external function uses
- The array is created and the lines are loaded from the file into it
- The array contains the correct contents in the filetostrarray() function

What DOESN'T work:
- load_paragraph() doesn't have access to the strings in the array and crashes the program when trying to display them

In void load_paragraph():
string parfile=par_file(current_node);
int lines;
string *line;
filetostrarray(parfile, &lines, line);
In filetostrarray
void filetostrarray(string file, int* lines, string *readlines) {
 *lines=lines_in_file(file);
 if (*lines) { fstream line_in(file.c_str(), ios::in);
			  readlines=new string[*lines];
			  for &#40;int i=0; i<*lines; i++&#41; getline&#40;line_in, readlines&#91;i&#93;&#41;;
			  line_in.close&#40;&#41;;
			  line_in.clear&#40;&#41;; } }

Edited by the_fifth_horseman, 27 August 2010 - 07:03 PM.


#2 the_fifth_horseman

the_fifth_horseman

    Member Munchkin

  • Members
  • PipPipPip
  • 59 posts

Posted 27 August 2010 - 07:20 PM

:angry:
Another half an hour of trial and error resulted in a solution.

EDIT: Wrong code.

Edited by the_fifth_horseman, 28 August 2010 - 08:56 AM.


#3 Qbix

Qbix

    AR-coholic

  • Members
  • PipPipPipPipPipPip
  • 605 posts

Posted 28 August 2010 - 06:56 AM

I must be blind, but how do the 2 posts differ ?

#4 the_fifth_horseman

the_fifth_horseman

    Member Munchkin

  • Members
  • PipPipPip
  • 59 posts

Posted 28 August 2010 - 08:56 AM

They didn't, I posted the wrong code.  :angry:

In void load_paragraph():
string parfile=par_file&#40;current_node&#41;;
int lines;
string *line;
filetostrarray&#40;parfile, &lines, &line&#41;;
void filetostrarray&#40;string file, int* lines, string **readlines&#41; { 
*lines=lines_in_file&#40;file&#41;;
 if &#40;*lines&#41; { fstream line_in&#40;file.c_str&#40;&#41;, ios&#58;&#58;in&#41;;
			  *readlines=new string&#91;*lines&#93;;
			  for &#40;int i=0; i<*lines; i++&#41;
						   { getline&#40;line_in, &#40;*readlines&#41;&#91;i&#93;&#41;;}
			  line_in.close&#40;&#41;;
			  line_in.clear&#40;&#41;; }
 }

Edited by the_fifth_horseman, 28 August 2010 - 08:59 AM.




Reply to this topic