I have a file which contains data in this manner-
1, 20.6, 33, 45, 67
2, 58.9, 54, 644, 233
3, 67.2, 67, 345, 889
.
.
.
.

where the second column contains float data and the others are all integers. I need to read this file in my program and use the numbers seperately. And can i use strtok() function here to seperate the numbers delimiting by the ',' ? If anyone has a solution plz let me know..

Recommended Answers

All 4 Replies

this snippet does no error checking, and is full of assumptions, but I'm posting it here so you get an idea of how strtok() could work.

//get subsequent lines into a char buffer
while (fgets(line,MAX_LINE_LEN,file_ptr))
{
   // tokenize the first item by comma delimiter
   line_ptr = strtok(line,",");

   while(line_ptr != NULL)
   {
      // if there's a decimal point, assume token is float (double)
      if (strstr(line_ptr,"."))
         floatArray[floatIndex++] = atof(line_ptr);

      // otherwise, it's asssumed to be an integer
      else
         intArray[intIndex++] = atol(line_ptr);
         
      // tokenize subsequent items by comma delimiter
      line_ptr = strtok(NULL,",");
      
   }
}

Thanks for the code. But the main point here is to store each column values in the file in different arrays coz i have to use those stored array values further in the program. Since i need to store all the values in different arrays which are here in this case separated by a ",".

commented: durr -1

If you already know how to use strtok, why did you use that in your topic title? Well anyway, I think you want something like this:

int r, c;
int arr[numRows][numCols];
while(/*there's another line*/)
{
  for(c = 0; c < 4 /*num cols*/; c++)
  {
    arr[r][c] = /*data read*/;
  }
  r++;
}

Thanks for the code. But the main point here is to store each column values in the file in different arrays coz i have to use those stored array values further in the program. Since i need to store all the values in different arrays which are here in this case separated by a ",".

well... maybe if you would learn how to ask questions properly, you would have titled your question "using arrays" and asked how to index arrays, rather than ask how to use strtok().

i don't know, i'm just sayin'


.

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.