• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 213
  • Last Modified:

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
Asked:
beckham711_atapibdboi2000
  • 2
1 Solution
 
Julian HansenCommented:
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
 
Julian HansenCommented:
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

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now