scanf中的正则表达式

来源:互联网 发布:淘宝助手怎么用 编辑:程序博客网 时间:2024/05/01 07:18

1、定制自己的扫描集 %[abc]、%[a-z]、%[^abc]、%[^a-z],比isdigit()、isalpha()更加灵活。[]内是匹配的字符,^表示求反集。
int i;
char str[80], str2[80];
// scanf("%d%[abc]%s", &i, str, str2);  
// printf("%d %s   %s\n",i,str,str2);
// scanf("%[a-zA-Z0-9]", str);
// scanf("%[^abce]", str);
scanf("%[^a-z]", str);
printf("%s\n",str);

2、读入一个地址并显示内存地址的内容
int main(void)
{
char ch='c';
printf("%p\n", &ch); // print the address of ch.
char *p;
cout<<"Enter an address: ";
scanf("%p", &p);     //input the address displayed above
printf("Value at location %p is %c\n",p,*p);
return 0;
}

3、丢弃不想要的空白符:scanf("%c %c");

4、控制字符串中的非空白符:导致scanf()读入并丢弃输入流中的一个匹配字符。"%d,%d";

5、压缩输入:在格式码前加上*,则用户就可以告诉scanf()读这个域,但不把它赋予任何变量。
    scanf("%c%*c, &ch); 使用此方法可以在字符处理时吃掉多余的回车。


例1:从<sip:tom@172.18.1.133>中提取tom
    const char* url = "<sip:tom@172.18.1.133>";
    char uri[10] = {0};
   sscanf(url, "%*[^:]:%[^@]", uri);
    cout << uri << endl;

例2:从iios/12DDWDFF@122中提取12DDWDFF
    const char* s = "iios/12DDWDFF@122";
    char buf[20];
    sscanf(s, "%*[^/]/%[^@]", buf);
    cout << buf << endl;