首页 > 代码库 > scanf()小技巧,使用%[]进行字符串解析

scanf()小技巧,使用%[]进行字符串解析

//=========Sample 1==========    char line[256];    char * name;    fgets(line, 256, stdin);    const char * p = strchr(line, ,);    name = new char[p - line + 1];    strncpy(name, line, p - line);    name[p-line] = \x00;    sscanf(p+1, "%d,%d,%d,%d,%d,%d", &age, &id,             &grades[0], &grades[1], &grades[2], &grades[3]);        delete []name;//=========Sample 2===========    char name[32];        scanf("%[^,],%d,%d,%d,%d,%d,%d", name, &age, &id,             &grades[0], &grades[1], &grades[2], &grades[3]);
//====================input:  Tom,18,7817,80,80,90,70//====================
上面的例子需要解析一行输入,里面的数据项用”,”分割,平常的“%s”是不能识别逗号分隔的,只能识别空白字符,例如空格、制表符、回车。
这里使用“%[]”来匹配,“%[^,]”的意思是匹配到“,”为止,包含“,”,
“%[^,],”的意思是匹配到“,”为止,包含“,”。

附(man scanf)节选 :
SCANF(3)                  Linux Programmer‘s Manual                 SCANF(3)
...
   Conversions       The following type modifier characters can appear in a conversion       specification:

 

       [      Matches a nonempty sequence of characters from the specified              set of accepted characters; the next pointer must be a pointer              to char, and there must be enough room for all the characters              in the string, plus a terminating null byte.  The usual skip              of leading white space is suppressed.  The string is to be              made up of characters in (or not in) a particular set; the set              is defined by the characters between the open bracket [              character and a close bracket ] character.  The set excludes              those characters if the first character after the open bracket              is a circumflex (^).  To include a close bracket in the set,              make it the first character after the open bracket or the              circumflex; any other position will end the set.  The hyphen              character - is also special; when placed between two other              characters, it adds all intervening characters to the set.  To              include a hyphen, make it the last character before the final              close bracket.  For instance, [^]0-9-] means the set              "everything except close bracket, zero through nine, and              hyphen".  The string ends with the appearance of a character              not in the (or, with a circumflex, in) set or when the field              width runs out.

scanf()小技巧,使用%[]进行字符串解析