例子

    1. #include <iostream>
    2. #include <stddef.h>
    3. #include <stdlib.h>
    4. #include <stdio.h>
    5. #include <string.h>
    6. // 跳过数据 %*s, %*d
    7. void test01() {
    8. char *str = "12345abcde";
    9. char buf[1024] = {0};
    10. sscanf(str, "%*d%s", buf);
    11. printf("buf:%s\n", buf);
    12. }
    13. void test02() {
    14. //忽略字符串到空格或者\t
    15. char *str = "abcde\t123456";
    16. char buf[1024] = {0};
    17. sscanf(str, "%*s%s", buf);
    18. printf("buf:%s\n", buf);
    19. }
    20. void test03() {
    21. // %[a-z] 匹配a到z中任意字符(尽可能多的匹配)
    22. char *str = "12345abcde";
    23. char buf[1024] = {0};
    24. sscanf(str, "%*d%[a-c]", buf);
    25. printf("buf:%s\n", buf);
    26. }
    27. void test04() {
    28. //%[aBc] 匹配a、B、c中一员,贪婪性
    29. char *str = "aABbcde";
    30. char buf[1024] = {0};
    31. sscanf(str, "%[aAb]", buf);
    32. printf("buf:%s\n", buf);
    33. }
    34. void test05() {
    35. //%[^a] 匹配非a的任意字符,贪婪性
    36. char *str = "aABbcde";
    37. char buf[1024] = {0};
    38. sscanf(str, "%[^c]", buf);
    39. printf("buf:%s\n", buf);
    40. }
    41. void test06() {
    42. char *str = "aABbcde12345";
    43. char buf[1024] = {0};
    44. sscanf(str, "%[^0-9]", buf);
    45. printf("buf:%s\n", buf);
    46. }
    47. void test07() {
    48. char *ip = "127.0.0.1";
    49. int num1 = 0, num2 = 0, num3 = 0, num4 = 0;
    50. //把ip录入进去
    51. sscanf(ip, "%d.%d.%d.%d", &num1, &num2, &num3, &num4);
    52. printf("num1:%d\n", num1);
    53. printf("num2:%d\n", num2);
    54. printf("num3:%d\n", num3);
    55. printf("num4:%d\n", num4);
    56. }
    57. void test08() {
    58. char *str = "abcde#12uiop@0plju";
    59. char buf[1024] = {0};
    60. sscanf(str, "%*[^#]#%[^@]", buf);
    61. printf("buf:%s\n", buf);
    62. }
    63. int main() {
    64. // test01();
    65. // test02();
    66. // test03();
    67. // test04();
    68. // test05();
    69. // test06();
    70. // test07();
    71. test08();
    72. getchar();
    73. return 0;
    74. }