Reading in a string from a file and need to preform basic math equations with it, therefor assuming it can't be in string form. I am attempting to use ATOF but am getting 0's and nan's in return...any suggestions?

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

int main()
{
/*Define Everything*/
FILE * fp;
FILE * fp2;
char String[50000];
char read[500000];
char out[500000];
char Diff[100];
float Decimal;
int i, j;

strcpy(read, "GREP_MARK");
strcpy(out, "Average");
fp = fopen(read,"r");
fp2 = fopen(out, "w+");

while (!feof(fp))
{
i = 0;
j = 334;
Decimal = 0;
fgets(String, 50000, fp);
while (i<=1)
{
Diff = String[j];
j++;
i++;
}
Decimal = atof(Diff);
fprintf(fp2,"The int is: %f\n", Decimal);
}
}

The string is numbers like -2.987633 and its the decimal places giving me a hard time.

If the file contains only numbers why are you reading them as strings?

float number;
while( fsprintf(fp,"%f", &number) > 0)
{
   // do something with number
}

The file isn't all numbers. It looks like:
"Name: 45.02943 Name2: 092734 Name3: 2398408.97 Difference: -1.094622" x 200 rows identiacal to this
and I need to find the average of the numbers in the Difference column.

I think the problem is assuming that -1.094622 starts at position 334. That may or may not be true depending on the contents of all previous data in that line. A better and safer way to do it is to call strstr() to locate "Difference:" and go from there.

char* ptr = strstr(String,"Difference:");
if( ptr != NULL)
{
   // advance to colon
   while( *ptr != ':' )
      ++ptr;
   // advance one more position
   ++ptr;
   Decimal = atof(ptr);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.