• Status: Solved
• Priority: Medium
• Security: Public
• Views: 226

extracting data from text file

i am using C++, i am a newbie in C++. How do i extract some data in a textfile into the program using the function open files. The data that i wan is from 6 line onward, how do i store this data into a array for easy manuplulating.
file:
----------------------------------------------------------

VG= -0.5 to 1 in 0.01 step
VD= 0.05 to 1 in 0.95 step
NO. VD VG ID IG
V V A A
1 0.05 -0.5 2.072E-10 -3.6913E-10
2 0.05 -0.49 1.9702E-10 -3.5064E-10
----------------------------------------------------------
0
beckham711_atapibdboi2000
• 2
1 Solution

Commented:
A simple solution would be as shown below (if you want to work with the values as float/double - although with 10^(-10) you might have some problems with storing such small numbers in a double. If you want to store them as strings then stop after the marked line.

#include math

FILE * fp = fopen ( "filename", "rt" ) ;
char szLine[256] ;
int i, count = 0 ;
char s[4][256] ;
double fvalues[4] ;

if ( fp )
{
while ( !feof(fp) && count++ < 6 )   fgets ( szLine, 256, fp ) ;
// you should now be at line six

fscanf ( fp, "%ld, %s %s %s %s", &id, s[0], s[1], s[2], s[3] ) ;   // To store as strings stop here
for ( i = 0 ; i < 4 ;i++ )
fvalues[i] = Convert(s[i]) ;
}

...

double Convert ( char * s )
{
double fval ;
char * p  ;
int exp ;
// convert from scientific notation to float

if ( ( p = strchr ( s, 'E' ) ) )
{
*p = 0 ;
fval = atof ( s ) ;
exp = atoi ( p+1) ;
fval = fval * pow(10,exp) ;
}
else fval = atof ( s ) ;

return fval ;
}
0

Commented:
Above is overly complex you can drop the Convert function and leave it with

#include math

FILE * fp = fopen ( "filename", "rt" ) ;
char szLine[256] ;
int count = 0 ;
double fvalues[4] ;

if ( fp )
{
while ( !feof(fp) && count++ < 6 )   fgets ( szLine, 256, fp ) ;
// you should now be at line six

while ( !feof ( fp ) )
{
fscanf ( fp, "%ld, %f %f %f %f", &id, fvalues[0], fvalues[1], fvalues[2], fvalues[3] ) ;
// other processing
}

fclose ( fp );
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.