c - 如何让 sscanf 在具有结构的 unix 中运行?
问题描述
我正在尝试按照评论所述进行操作,但是我的 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);
推荐阅读
- php - Laravel Nexmo 无效签名
- webstorm - Emmet 在 .php 文件中无法在 WebStorm 中工作
- python - Python中逗号运算符的含义是什么?
- javascript - 如何填充表 td
- python - 直方图范围之外的点从图中丢弃
- jquery - jQuery Textarea - 删除间距但在每个单词后添加换行符
- lucene - Lucene:构面范围取决于返回的结果
- node.js - 如何从渲染 html Sails js 创建文件
- visual-studio-code - 禁用 VSCode 提示:“是否要保存工作区配置”?
- wordpress - Echo 变量 ID 在 WordPress 中不起作用