Click here to Skip to main content
15,894,410 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a file which has the contents as follows :
S# Name From To Train# DOJ Fiar
1 Srikumar COCHIN KOLKATTA 12515 12/12/2012 530

Now, I need to get only the columns From, To and DOJ.

I have tried,

fscanf(fp,"%s,%s,%s",frm,to,doj);

But it is showing the first 3 columns.

And I need to store the date in to an array.

Please help.
Posted
Updated 18-Nov-12 23:28pm
v2

fscanf works as designed. It takes the first three strings.

I have two options:
1)
Add "dummys" like
C++
fscanf("%s %s %s %s %s %s", dummy1, dummy2, from, to, dummy3, doj);


Allways pay attention on the buffer size of your target strings!

2)
Read the whole line with fgets() and seperate the string with srtok

You can find more on strok here e.g. http://www.cplusplus.com/reference/clibrary/cstring/strtok/[^]
 
Share this answer
 
Comments
srmohanr 19-Nov-12 5:33am    
Thanks man
Andy411 19-Nov-12 5:35am    
you're welcome
You can use the * specification to skip fields that you are not interested in. You should also use the width specification to limit the number of characters read for any field, to guard against buffer overrun. Something like:
C++
char szFrom[32];
char szTo[32];
char szDOJ[12];
int nFieldCount = fscanf(fpInput, "%*s %*s %32s %32s %*s %12s %*s", szFrom, szTo, szDOJ);

I'm not sure what you mean by "I need to store the date in to an array.".
 
Share this answer
 
Comments
srmohanr 19-Nov-12 5:57am    
Thanks for your help man. Please omit the later part.
CPallini 19-Nov-12 6:18am    
Wow, a trick I didn't know.
My 5.
Richard MacCutchan 19-Nov-12 6:47am    
I only discovered it recently while researching on MSDN.
Mohibur Rashid 19-Nov-12 7:47am    
+5, interesting
Cannot you simply discard the info you don't need?
e.g.
C
int s; // will be discarded
// use 'large-enough' buffers.
char n[0x20]; // will be discarded
char f[0x20];
char t[0x20];
int d;


if ( fscanf(fp, "%d %s %s %s %d", &s, n, f, t,&d) != 5)
{
  // handle error
}

printf("from %s to %s doj %d\n", f, t, d);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900