当前位置: 代码迷 >> 综合 >> 从字符串格式化输入数据:sscanf
  详细解决方案

从字符串格式化输入数据:sscanf

热度:75   发布时间:2023-11-09 15:16:02.0

代码—1:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>int main()
{int day, year;char weekday[20], month[20], dtm[100];strcpy( dtm, "Saturday March 25 1989" );sscanf( dtm, "%s %s %d %d", weekday, month, &day, &year );printf("%s %d, %d = %s\n", month, day, year, weekday );strcpy( dtm, "hello_1" );sscanf( dtm, "%s_%d", weekday, &day);day++;printf("%s %d\n", weekday, day);
 return(0);
}

执行如下:

March 25, 1989 = Saturday hello_1 26

代码—2:
※使用正则表达式

#include <stdio.h>
#include <stdlib.h>
#include <string.h>int main()
{int day, year;char weekday[20], month[20], dtm[100];strcpy( dtm, "Saturday March 25 1989" );sscanf( dtm, "%s %s %d %d", weekday, month, &day, &year );printf("%s %d, %d = %s\n", month, day, year, weekday );strcpy( dtm, "hello_1" );sscanf( dtm, "%[a-zA-Z]_%d", weekday, &day);day++;printf("%s %d\n", weekday, day);
 return(0);
}

执行如下:

March 25, 1989 = Saturday hello 2