我正在尝试按照注释状态进行操作,但是我的sscanf语句不起作用。我应该在使用sscanf之前为dob初始化变量吗?我的程序不断警告我它们没有被初始化,但是在运行之后,它会跳过我的sscanf。
#include <stdio.h>
// define a structure called dob that contains an array for month,
// an integer for day, and an integer for year
typedef struct{
char month[3];
int day;
int year;
}dob;
int main(int argc, char *argv[]) {
// declare a variable bday whose type is the structure dob
dob bday;
// show sscanf() statements to get the values entered at the
// command line into the variable bday if user enters the following:
// Jan 31 1967 = input
// ./a.out Jan 31 1967
sscanf("%s %i %i", bday.month, bday.day, bday.year);
// finish the printf statement below
printf("Your birthday is: %s %d, %d\n", bday.month, bday.day, bday.year);
return 0;
}
确保月份可以容纳3个字符和一个空终止符:char month[4];
初始化dob,以及用于输入的缓冲区:
char inbuf[80] = {0};
dob bday = {0};
不要忘记让用户输入一些数据:
fgets(inbuf, sizeof(inbuf)-1, stdin);
正确调用sscanf,使用输入字符串先扫描格式字符串,然后再扫描要修改的成员的地址:
sscanf(inbuf, "%3s %i %i", bday.month, &bday.day, &bday.year);