I think I have a rather straightforward problem, but I'm relatively new to C. I have an input file that looks like this:

0.682448 0.53791 0.61727 0.48714
0.297144 0.29688 0.40549 0.68233
0.426100 0.62057 0.25095 0.54782
0.673007 0.51040 0.25476 0.35149
0.641339 0.49815 0.54557 0.42673
0.268030 0.38949 0.48841 0.56580

I need to compute x=p*log(p), where p corresponds to one element in my array, say 0.682448. and then, I need to add, let's say, the first 8 'x' values (the first two rows). I need to send that value to an external file, and keep doing it until I reach the end of the file.

I'm not sure how to import the individual float values and how to advance to the next line and how to stop after 2 lines and sum all the values up and then resume the process. I can have the external file formated so that the individual values are either separated by a single space or by a TAB.

I appreciate any suggestions.


8 Years
Discussion Span
Last Post by Prabakar

you can use fscanf("%f", ...) to input the values from the file. Use a counter integer to count 8 fscnaf().

int i;
float nums[8];
FILE* in = fopen("filename.txt");
for(i = 0; i < 8; i++)
    fsscanf("%f", &nums[i]);

terrific, that worked like a champ. thanks.

one more question, though: in mathematics, the difference between log and ln is that log uses base 10 and ln uses base e. I need to use ln base e, however, it looks like the 'math.h' does not have it in the form that I'd expect. do you know how I can get the ln base e?

this is the working code, however, it uses log base 10

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

  FILE *pFile1;
  FILE *pFile2;
  int i,a;
  float p[32], x[32], sum;

  pFile1 = fopen ("in2.txt","r");  
  pFile2 = fopen ("out2.txt","w");  

  for(a = 0; a < 6; a++)

    for(i = 0; i < 32; i++)
      fscanf(pFile1, "%f", &p[i]);

    for(i = 0; i < 32; i++)

    for(i = 0; i < 32; i++)

    fprintf(pFile2,"%f", sum);
    fprintf(pFile2, "\n");

  fclose (pFile1);  
  fclose (pFile2);  


Ya, and for any other bases you have the formula

log a ( base b ) = log a ( base c ) / log b ( base c )

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.