首页 > 解决方案 > 如何让 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;

}

标签: cunixscanfstructure

解决方案


确保月份可以容纳 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);

推荐阅读