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.

转载于:https://www.cnblogs.com/brucex/p/scanf-string-tips.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值