我正尝试按照评论中的说明进行操作,但是我的 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), stdin);
正确调用 sscanf,在格式字符串之前输入要扫描的字符串(注意,将字符串扫描限制为 3 个字符以保证内存安全),然后是要修改的成员的地址:
sscanf(inbuf, "%3s %i %i", bday.month, &bday.day, &bday.year);
关于c - 如何让 sscanf 在具有结构的 unix 中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633117/