954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read comma separated data from a text file

Hi there,

I am trying to make a piece of code in C that:

1. opens a specified file,
2. Reads the data in the file and separates it into two arrays, based on the position of commas,
3. Converts the strings into doubles and then perfoms some manipulation on them,
4. returns the new values to a second text file.

I can do 1,3 & 4, just can't seem to get point 2 to work. The data I have is in the format:

0.000,1
0.001,2
0.002,4
0.003,1
0.004,5
0.005,3

and I want to end up with two arrays of the form:

a[6] = {0.000,0.001,0.002,0.003,0.004,0.005};
b[6] = {1,2,4,1,5,3};

Any offers?

cheers, Ravenous.

ravenous
Posting Pro
516 posts since Jul 2005
Reputation Points: 269
Solved Threads: 92
 

looking at the strings library, you could do the following:

char *ptrtocomma;

if(ptrtocomma=strchr(Inputstringname, ',')!=NULL)
{
outputarray[i]=*++ptrtocomma;
i++;
}


strchr returns a character pointer to the first occurance of the second argument (a character) in the character array designated by the first argument.

Drowzee
Posting Whiz in Training
245 posts since Jul 2005
Reputation Points: 22
Solved Threads: 5
 
while(fgets(line, sizeof line, file)}
{
   if(sscanf(line, "%lf,%d", &a[i], &b[i]) == 2)
   {
      ++i;
   }
}
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

That's much nicer... Wow.

Drowzee
Posting Whiz in Training
245 posts since Jul 2005
Reputation Points: 22
Solved Threads: 5
 
while(fgets(line, sizeof line, file)}
{
   if(sscanf(line, "%lf,%d", &a[i], &b[i]) == 2)
   {
      ++i;
   }
}

Hi, how if each row contains large number of elements in 1 row of a large matrix? For example I have a matrix of 100x100 which already stored in a text file, each line contains 100 elements of 1 row of the matrix, seperated by a tab (\t). How could I read the file back into a matrix structure?

Many thanks,
Fantabk

fantabk
Newbie Poster
1 post since Apr 2007
Reputation Points: 9
Solved Threads: 0
 

Show us what you have and we can help you fix it. But do it in an new thread. It's not nice to hijack someone else's thread.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You