为什么scanf在第一个循环之后不能输入?

问题描述:

我正在尝试在结构中保存天气数据。在下面的例子中,当我使用scanf时,它对第一个循环来说工作正常,但是从第二个循环中,scanf被跳过并且只是执行了printf语句。我怎样才能让scanf在整个循环中获得输入。这里是我的代码:为什么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; 
} 
+0

看看这里:http://*.com/questions/26345914/c-scanf-in-loop-continues-automaticly-without-input?rq=1 – saruftw

+1

经常检查函数的结果!什么'scanf'返回? – Olaf

+0

这并不是说scanf没有执行。它可能会从循环的第一次迭代中读取由stdin输入的一些现有输入。尝试在每次迭代后打印值。这可能会帮助你。 – Jay

格式错误。 scanf("\n%[\n]s"...


scanf()为0或更多的白色空间由于"\n"

第一丢弃然后扫描换行符由于"%[\n]"。由于此时的输入是从“今天”开始的“t”。扫描失败并停止。

后来scanf("\n%d",&(pinfo+loop)->h_temp);试图读入't'作为一个数字,也失败了。事情就会变得更糟。

由于@rici评论,OP可能想"\n%[^\n]"

主要故障确实是代码没有检查scanf()的结果来验证发生的有效输入。

推荐:

1)使用" ",而不是"\n"跳过可选的空白。两者都是一样的。 " "是惯用的。

2)使用宽度有限的格式,如用于" %79[^\n]"char notes [80];

3)始终检查scanf()结果等if (1 !- scanf("\n%d",&(pinfo+loop)->h_temp) { puts("temp fail"); return -1; }

4)看到倾倒scanf()所有的使用和使用fgets()代替。


另外:

ctime()再使用相同的缓冲液中。

返回值指向一个静态分配的字符串,可能会被随后调用任何日期和时间函数覆盖。

// (pinfo+loop)->date = ctime(&curtime); 
// Make duplicate and remember to free when done. 
(pinfo+loop)->date = strdup(ctime(&curtime));