C语言中将字符串day="3",time=“08:12:25”中四个数据提取到整形变量结构体Timing(day,hour,min,sec}中
时间: 2024-02-16 18:03:27 浏览: 98
你可以使用C语言中的字符串处理函数和结构体来实现这个功能。具体的步骤如下:
1. 定义结构体Timing,包含day、hour、min、sec四个成员变量。
```
struct Timing {
int day;
int hour;
int min;
int sec;
};
```
2. 定义字符串day和time。
```
char *day = "3";
char *time = "08:12:25";
```
3. 使用字符串处理函数sscanf将day和time中的数据提取到对应的整形变量中。
```
int day_int;
int hour_int;
int min_int;
int sec_int;
sscanf(day, "%d", &day_int);
sscanf(time, "%d:%d:%d", &hour_int, &min_int, &sec_int);
```
4. 将提取出来的整形变量赋值给Timing结构体的成员变量。
```
Timing timing;
timing.day = day_int;
timing.hour = hour_int;
timing.min = min_int;
timing.sec = sec_int;
```
最终的代码如下:
```
#include <stdio.h>
struct Timing {
int day;
int hour;
int min;
int sec;
};
int main() {
char *day = "3";
char *time = "08:12:25";
int day_int;
int hour_int;
int min_int;
int sec_int;
sscanf(day, "%d", &day_int);
sscanf(time, "%d:%d:%d", &hour_int, &min_int, &sec_int);
Timing timing;
timing.day = day_int;
timing.hour = hour_int;
timing.min = min_int;
timing.sec = sec_int;
printf("day: %d, hour: %d, min: %d, sec: %d\n", timing.day, timing.hour, timing.min, timing.sec);
return 0;
}
```
阅读全文