问题描述
我有一个文件,其内容如下:
S#名称从要训练的#DOJ Fiar
1 Srikumar COCHIN KOLKATTA 12515 2012/12/12 530
现在,我只需要获取From,To和DOJ列.
我已经尝试过了,
fscanf(fp,%s,%s,%s",frm,to,doj);
但它显示的是前三列.
而且我需要将日期存储在数组中.
请帮忙.
Hi,
I have a file which has the contents as follows :
S#NameFromToTrain#DOJFiar
1Srikumar COCHINKOLKATTA 1251512/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.
推荐答案
fscanf("%s %s %s %s %s %s", dummy1, dummy2, from, to, dummy3, doj);
始终要注意目标字符串的缓冲区大小!
2)
使用fgets()读取整行,并使用srtok分隔字符串
您可以在这里找到更多关于行程的信息 http://www.cplusplus.com/reference/clibrary/cstring/strtok/ [ ^ ]
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/[^]
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.".
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);
这篇关于用C语言读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!