Hello,

I'm trying to read lines from a file and strtok it into a double array to work with the numbers.
The numbers are separated by ',' and I'm trying to fill array (line[]) with these numbers.

This is part of the code.

while(1) 
{
  //we will scan all the lines in the file 
  fscanf(separators_f, "%s", data);
  if(feof(separators_f))
  {
    break;
  }
  i=0;
  num=strtok(data, SEPARATOR);
  //line will contain the numbers without the separators 
  while(num!=NULL)
  {
    printf("\n num is:%s\n", num);
    line[i]=atof(num);
    num=strtok(NULL, SEPARATOR);
    i++;
  }
  printf("\n%f   %f\n", line[0], line[1]);

my file contains:
a.txt:
2,4
1.2,-2

for some reason, in the first line, line[0] always contains 0 !
but the second line works fine and I get the real results.. now if the text file contains an empty line in the beginning, everything works fine!

CAN SOMEONE HELP PLEASE?

fscanf() won't work for you if the line contains any spaces or tabs. Its better to just use fgets() to avoid that problem. And a better way to code the while statement is like this:

while( fgets(data, sizeof(data),separators_f) )
{
   char* ptr = strtok(data,",");
   i = 0;
   int line[5] = {0}; // this could be defined somewhere else
   while( ptr )
   {
       char* endptr = 0;
       line[i++] = strtod(ptr,&endptr);
       // at this point you might want to do some error checking
       // to make sure that strtod() worked ok.
       //
       ptr = strtok(NULL,",");
   }
}

Thanks for the reply.
The strange thing is that my code works fine for the next lines! It only have problems with the first line. (it stores 0 in line[0] instead of the real value, but store the right value for line[1]).
for the next lines, it works fine.
what could it be? how can I fix that? I tried to fgets it but still..

change it like I showed you and it should work ok. Also check the file to see if there is anything at the beginning of the first line that would cause that behavior, such as a blank line.

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.