【问题标题】:Memory Issue Preventing Input into Struct?内存问题阻止输入到结构?
【发布时间】:2018-03-06 20:41:58
【问题描述】:

我不明白为什么最后一行要求用户输入权重没有被执行。会不会是内存问题?还是我写错了结构?还是我错误地编写了对 scanf() 的调用?还是以上所有?

#include <stdio.h>

struct date{
  int month;
  int day;
  int year;
};

struct healthProfile{
  char firstName[20];
  char lastName[20];
  struct date birthday;
  float height; //inches
  float weight; //pounds
};



int main(void)
{
  struct healthProfile patient1;

  printf("%s\t", "Please enter the patient's first name:");
  scanf("%s", patient1.firstName);


  printf("%s\t", "Please enter the patient's last name:");
  scanf("%s", patient1.lastName);

  printf("%s\t", "Please enter the date of birth(mm/dd/yyyy)");
  scanf("%2i/%2i/%4i", &patient1.birthday.month, &patient1.birthday.day, &patient1.birthday.year);

  printf("%s\t", "Please enter the patient's height in inches");
  scanf("%.2f", &patient1.height);

  printf("%s\t", "Please enter the patient's weight in pounds");
  scanf("%.2f", &patient1.weight);



  return 0;
}

【问题讨论】:

  • 你怎么知道不是?
  • 这个程序到底是做什么的?它只是正常退出,崩溃还是其他?
  • 是的,正常退出。除了最后一行,我可以输入其他所有内容
  • 请澄清您的问题,您的意思是程序不会等待用户输入重量输入。
  • 在 scanf 中使用 %d 而不是 %i。否则如果他们在出生月份写09你会遇到麻烦

标签: c input struct scanf


【解决方案1】:

printf 不同,scanf 的格式说明符不需要精度。编译器应该警告你:

x1.c: In function ‘main’:
x1.c:34:3: warning: unknown conversion type character ‘.’ in format [-Wformat=]
   scanf("%.2f", &patient1.height);
   ^
x1.c:34:3: warning: too many arguments for format [-Wformat-extra-args]
x1.c:37:3: warning: unknown conversion type character ‘.’ in format [-Wformat=]
   scanf("%.2f", &patient1.weight);
   ^
x1.c:37:3: warning: too many arguments for format [-Wformat-extra-args]

去掉精度就可以正常阅读了:

printf("%s\t", "Please enter the patient's height in inches");
scanf("%f", &patient1.height);

printf("%s\t", "Please enter the patient's weight in pounds");
scanf("%f", &patient1.weight);

【讨论】:

  • 正确,但不是问题的原因。
  • 另外,printfs 应该被刷新,因为没有换行。因此,您可能会得到“无输入”。
【解决方案2】:

当您从控制台接收输入时,它是行缓冲的,但 %f 格式说明符仅提取数字数据,将换行符(至少)留在缓冲区中。下一个输入丢弃前导空格(上一次调用的换行符),但对于最后一个输入,您需要或丢弃它。一种方式:

  int c ;
  while ((c = getchar()) != '\n' && c != EOF) { }
  scanf("%f", &patient1.weight);

然而,在任何不使用换行符的输入之后执行此操作是个好主意,并且在这种情况下更简单地将输入包装在一个函数中,例如 getfloat() 以减少重复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2014-04-24
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多