how to identify a field separator from scanf?

2019-01-18 16:05发布

问题:

I need to read a text file which has names with numbers like below.

rENLAg:12182
TgAlKd:19773
SSqUpz:16466
QYStPh:4113
CodNhz:28920
SgoIGz:25343

I need to separate the letters from the numbers.fscanf only identifies spaces, but not other field separators. Therefore how do I do it?

回答1:

One solution would be to use scan sets (see the entry for Conversion specifier [set] in the format specifiers table):

char buf[7];
int i;
/* Check result of fscanf(), which returns the number
   of assignments made, to ensure both 'buf' and 'i'
   were assigned values. */
if (fscanf(fp, " %6[^:]:%d", buf, &i) == 2)
{
}

where " %6[^:]" means skip any leading whitespace (new-line character from previous read for example) and read up to, but not including, the first : character but no more than 6 characters (to prevent buffer overrun).



标签: c scanf