c语言 sscanf,scanf,fscanf正则表达式用法

2020-01-06 18:27:45王振洲


char s[]="HELLOkitty” ;// 注意 : , 逗号在不 a-z 之间
sscanf( s, “%[^a-z]”, string ) ; // string=HELLO

%*[^=] 前面带 * 号表示不保存变量。跳过符合条件的字符串。


char s[]="notepad=1.0.0.1001" ;
char szfilename [32] = "" ;
int i = sscanf( s, "%*[^=]", szfilename ) ; // szfilename=NULL, 因为没保存
int i = sscanf( s, "%*[^=]=%s", szfilename ) ; // szfilename=1.0.0.1001

%40c 读取 40 个字符

The run-time
library does not automatically append a null terminator to the string, nor does reading 40 characters
automatically terminate the scanf() function. Because the library uses buffered input, you must press the ENTER key to terminate the string scan. If you press the ENTER before the scanf() reads 40 characters, it is displayed normally, and the library continues to prompt for additional input until it reads 40 characters

%[^=] 读取字符串直到碰到 '=' 号, '^' 后面可以带更多字符 , 如:


char s[]="notepad=1.0.0.1001" ;
char szfilename [32] = "" ;
int i = sscanf( s, "%[^=]", szfilename ) ; // szfilename=notepad 

如果参数格式是: %[^=:] ,那么也可以从 notepad:1.0.0.1001 读取 notepad

使用例子:


char s[]="notepad=1.0.0.1001" ;
char szname [32] = "" ;
char szver [32] = “” ;
sscanf( s, "%[^=]=%s", szname , szver ) ; // szname=notepad, szver=1.0.0.1001

总结: %[] 有很大的功能,但是并不是很常用到,主要因为:

1 、许多系统的 scanf 函数都有漏洞 . ( 典型的就是 TC 在输入浮点型时有时会出错 ).
2 、用法复杂 , 容易出错 .
3 、编译器作语法分析时会很困难 , 从而影响目标代码的质量和执行效率 .

个人觉得第 3 点最致命,越复杂的功能往往执行效率越低下。而一些简单的字符串分析我们可以自已处理。

C语言中scanf(),sscanf(),fscanf()的用法和区别

scanf(),sscanf(),fscanf()区别:
第一个是从控制台(键盘)输入;
第二个是从字符串输入;
第三个是从文件输入;
scanf
scanf()函数根据由format(格式)指定的格式从stdin(标准输入)读取,并保存数据到其它参数.


int main()
{
  int a,b,c;
  printf("输入:a,b,cn");
  scanf("%d,%d,%d",&a,&b,&c);
  printf("a = %d b = %d c = %d",a,b,c);
  return 0;
}

sscanf
函数sscanf()和scanf()类似, 只是输入从buffer(缓冲区)中读取.
sscanf与scanf类似,都是用于输入的,只是后者以屏幕(stdin)为输入源,前者以固定字符串为输入源