Monday, May 24, 2010

Creating an array of strings from a text document?

i am working on a C++ program that requires me to create an array of strings with at least 100 strings. all of which must be pulled from a text document. i can open the document in the program but i do not know how to place the strings into an array. please help.


pseudo-code, or real code will be helpful lol


thanks

Creating an array of strings from a text document?
#include %26lt;iostream.h%26gt;


#include %26lt;fstream.h%26gt;


#include %26lt;cstring.h%26gt;





int main()


{


int n;





ifstream d;


d.open("datafile.dat");





if (d)


{


d%26gt;%26gt;n;





while(!d.eof())


{


n++;


d%26gt;%26gt;n;





}








}


d.close();


string s[n];


d.open("datafile.dat");


int i=0;


if(d){ d%26gt;%26gt;s[i];


i++;


while(!d.eof()){


d%26gt;%26gt;s[i];


i++;


}


}


return 0;


}
Reply:Here is some code for you, fully commented and very compact, easy to understand variable names as well.





#include %26lt;iostream%26gt; //for basic console io


#include %26lt;fstream%26gt; //for file io


#include %26lt;string%26gt; //for string type


#include %26lt;cassert%26gt; //for assert()


using namespace std;





int main() {


///////////////////VARIABLE DECLARATIONS////////////////////////


ifstream infile; //variable for input of file;


/**/ infile.open("theFile.txt"); //associates file with variable


/**/ assert(!infile.fail()); //makes sure that infile has opened


string array[99]; //the array with only 100 reserved spaces


string holder; //a holder string for use with getline()


int i;





////////////////WHILE LOOP, READS FILE INTO ARRAY//////////


while(!infile.eof()) { //while its not end of infile file


getline(infile, holder); //gets line from infile stores into holder


array[i] = holder; //stores holder in array[i] where i=subscript


i = i + 1; //increments i by 1, allows use of next subscript


}





///////////////FOR LOOP OUTPUTS DATA TO SCREEN/////////


for (i = 0; i %26lt;= 99; i++) {


cout %26lt;%26lt; array[i] %26lt;%26lt; endl;


}





return 0;


}


No comments:

Post a Comment