how to identify a field separator from scanf?

后端 未结 1 419
北海茫月
北海茫月 2020-12-10 09:20

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
相关标签:
1条回答
  • 2020-12-10 09:42

    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).

    0 讨论(0)
提交回复
热议问题