Chinaunix首页 | 论坛 | 博客
  • 博客访问: 451077
  • 博文数量: 42
  • 博客积分: 1325
  • 博客等级: 中尉
  • 技术积分: 1312
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-13 18:00
个人简介

呵~~~呵~~~

文章分类

全部博文(42)

文章存档

2016年(3)

2015年(1)

2014年(2)

2013年(2)

2012年(7)

2011年(11)

2010年(3)

2009年(13)

我的朋友

分类: LINUX

2012-02-23 14:59:45

 
一、sscanf在直接处理逗号分隔符的时候,会发生错误。
程序如下:
  1. char *s = "aaa,bbb,ccc,ddd";
  2. char a[32],b[32],c[32],d[32];

  3. sscanf(s, "%s,%s,%s,%s\n", a, b, c, d);

  4. printf("[%s][%s][%s][%s]\n", a, b, c, d);

结果为:

  1. develop:/home/leon/test # ./a.out
  2. [aaa,bbb,ccc,ddd][][][]

二、解决。将sscanf内的格式化输出改为以下形式:

  1. sscanf(s, "%[^,],%[^,],%[^,],%s", a, b, c, d);

结果为:

  1. develop:/home/leon/test # ./a.out
  2. [aaa][bbb][ccc][ddd]

三、以下为MDSN的说明:
To read strings not delimited by space characters, a set of characters in brackets ([ ]) can be substituted for the s (string) type character. The corresponding input field is read up to the first character that does not appear in the bracketed character set. If the first character in the set is a caret (^), the effect is reversed: The input field is read up to the first character that does appear in the rest of the character set.

Note that %[a-z] and %[z-a] are interpreted as equivalent to %[abcde...z]. This is a common scanf function extension, but note that the ANSI standard does not require it.

理解:
%[]   指定字符集,即加了字符规则的'%s
^     取反
%[^,] 取非','的内容,直到遇到','

 

阅读(12816) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~