【发布时间】:2015-09-06 17:16:12
【问题描述】:
我正在尝试将天气数据保存在一个结构中。在下面,当我使用 scanf 时,它适用于第一个循环,但从第二个循环开始,scanf 被跳过,只执行 printf 语句。如何让 scanf 在整个循环中获取输入。这是我的代码:
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
struct weather
{
char *date;
int month;
int day;
int year;
unsigned int h_temp;
unsigned int l_temp;
int max_wind_speed;
int preciption;
char notes [80];
};
void collect_data (struct weather *pinfo)
{
int loop;
char yes_no[2];
time_t curtime; //declaring time variable
//storing current system time in the time variable
time(&curtime);
//storing current time to time structure
struct tm * wdate = localtime (&curtime);
for (loop=0;loop<4;loop++)
{
if (loop!=0)
{
(pinfo+loop)->date = ctime(&curtime);
(pinfo+loop)->day = wdate->tm_mday;
(pinfo+loop)->month = wdate->tm_mon;
(pinfo+loop)->year = wdate->tm_year;
}
/*else
{
recent_date(loop,wdate);
}*/
printf("\nEnter the high temperature of the day:");
scanf("\n%d",&(pinfo+loop)->h_temp);
printf("\nEnter the low temperature of the day:");
scanf("\n%d",&(pinfo+loop)->l_temp);
printf("\nEnter the maximum wind speed of the day:");
scanf("\n%d",&(pinfo+loop)->max_wind_speed);
printf("\nEnter the perciption of the day:");
scanf("\n%d",&(pinfo+loop)->preciption);
printf("\nDo you have any notes about the weather of the day (y/n):");
scanf("\n%s",yes_no);
if (strcmp(yes_no,"y")==0)
{
printf("\nNotes:\n");
scanf("\n%[\n]s",(pinfo+loop)->notes);
}
}
}
int main ()
{
struct weather info [4];
collect_data(info);
return 0;
}
【问题讨论】:
-
总是检查函数的结果!
scanf返回什么? -
\n在scanf模式中的作用与空格完全相同:导致任意数量的空格被跳过。但是%d和%s无论如何都会这样做。所以scanf("\n%d", &val)和scanf("%d", &val)没有区别。最好使用第二个。此外,您的notes字段只能容纳 79 个字符和一个 NUL 终止符,因此您应该使用scanf(" %79[^\n]", pinfo[loop].notes);填写它。 (%[^\n]s中的s只会匹配文字s,这不太可能,因为输入中的下一个字符(如果有)必须是\n,除非超出限制。) -
@user3629249 “系统函数 scanf() 在遇到任何空白时停止输入”不正确。这取决于格式。
-
100, 75, 40, 30, "y", "今天是记录的最高温度"。这些是第一个循环的输入
标签: c arrays pointers structure scanf