scanf()小技巧,使用%[]进行字符串解析
2014-11-26 10:43
501 查看
//=========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.
相关文章推荐
- 使用com.google.gson包进行json字符串的构造与解析
- eval解析JSON中的注意点 在JS中将JSON的字符串解析成JSON数据格式,一般有两种方式: 1.一种为使用eval()函数。 2. 使用Function对象来进行返回解析。 使用eval
- List的排序。在一个list里面放入"1","2"..."10","11"...,"99999","100000",使用字符串大小的顺序与解析成的数字的大小进行排序
- android开发小技巧(5)构建JSON字符串和解析简单使用
- C#中使用指针实现高效比较字符串的小技巧
- 一个关于使用c语言进行对文档读取替换特定字符串
- 使用 HttpResponse.Write 方法进行字符串串联
- 使用Java对字符串进行MD5加密以及验证
- 转:使用eval()解析JSON格式字符串应注意的问题
- C#中使用指针实现高效比较字符串的小技巧
- 使用Hashtable对字符串进行碰撞
- C#中使用指针实现高效比较字符串的小技巧
- 使用c语言解析字符串"176x144"中的数字
- 使用SQL2005自带扩展函数对字符串进行MD5加密(转)
- 使用Boost.Spirit实现四则运算字符串的解析
- java中字符串的比较,必须使用string1.equals(string2)来进行判断
- 对字符串数组进行排序,在冒泡法排序中使用compareTo()方法确定排序的顺序。
- 使用XSLT进行XML的解析
- SQL Server2005 使用FOR XML选项进行字符串的串联聚合
- [转]C#中使用指针实现高效比较字符串的小技巧