Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reading and storing file?

Status
Not open for further replies.

akashvij

Technical User
Mar 11, 2002
19
0
0
US
hello
i have to read a file and stor the data into the array. someone plz help me. i know how to read a file but don't know what should i do to store it in an array.Any help will be greatful.
akash
 
#include <iostream>
#include <fstream>
#include <string>

int CountLines( const char* file );
void OutArray( const std::string* s,int iSize );
void PopulateArray( std::string* s,int iSize,const char* file );

int main()
{
std::string* pFile=0;
std::string sPath=&quot;&quot;;
int iLines=0;

std::cout << &quot;Enter path to file:&quot;;
std::getline( std::cin,sPath );

iLines=CountLines( sPath.c_str() );
if( iLines==-1 ) exit( 0 );

pFile=new std::string[iLines];

PopulateArray( pFile,iLines,sPath.c_str() );
OutArray( pFile,iLines );

delete [] pFile;
return 0;
}

void PopulateArray( std::string* s,int iSize,const char* file )
{
std::ifstream inFile;
inFile.open( file );

for( int i=0;i<iSize;i++ )
std::getline( inFile,s );

inFile.close();
}

void OutArray( const std::string* s,int iSize )
{
for( int i=0;i<iSize;i++ )
std::cout << &quot;stringArray[&quot; << i << &quot;]&quot;
<< &quot; = &quot; << s <<
std::endl;
}

int CountLines( const char* file )
{
std::ifstream inFile;
std::string sTemp;
int iNewLines=0;

inFile.open( file );
if( inFile.fail() )
{
std::cout << &quot;No such file exists.&quot; <<
std::endl;
return -1;
}

while( !inFile.eof() )
{
std::getline( inFile,sTemp );
++iNewLines;
}
inFile.close();
return iNewLines;
}

//Open a text file and store each line into an array of
//string objects. Mike L.G.
mlg400@blazemail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top