C语言使用sscanf()解析字符串
最近刚看完《The C Programming Language》,果然是一本“小而美”的好书,最好能带着实际的目标去读,而不是走马观花地看个语法,相信每一个例子与习题都会带给你收获和提高。而我带着的目标,就是同事布置给我的“作业”:重构一个基于 C++ 实现的 IP Mapping 程序。
在查阅《C: A Reference Manual》后,感觉C语言库中可能没有解析CSV格式的原生函数,所以任务的第一步,就是造个解析CSV的轮子。(PHP是世界上最好的语言 :p )
而之前学习C的时候,在7.4格式化输入章节有这样一段介绍:
另外还有一个输入函数 sscanf,它用于从一个字符串(而不是标准输入)中读取字符序 列:
int sscanf(char *string, char *format, arg1, arg2, …)
它按照格式参数 format 中规定的格式扫描字符串 string,并把结果分别保存到 arg1、
arg2、…这些参数中。这些参数必须是指针。
于是我造了这么个木头轮子:
1 | |
果然不能跑:)
于是乎继续往后看,后面有这样一段:
假设我们要读取包含下列日期格式的输入行:
25 Dec 1988
相应的 scanf 语句可以这样编写:
int day, year;
char monthname[20];
scanf(“%d %s %d”, &day, monthname, &year);
因为数组名本身就是指针,所以,monthname 的前面没有取地址运算符&。
看完后更觉得没毛病了。去网上看看别人咋写的:
1 | |
好像看出了点什么,还是 RTFM 吧:
Reading Undelimited strings
To read strings not delimited by whitespace characters, a set of characters in brackets ([ ]) can be substituted for the s (string) type character. The set of characters in brackets is referred to as a control string. The corresponding input field is read up to the first character that does not appear in the control string. 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.
然后我把轮子改成了这样:
1 | |
run到飞起:)
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!