程序给出错误

时间:2010-07-07 10:14:46

标签: c

程序的逻辑非常清楚但是当它要求用户输入名称时。第二次要求输入名称,即在i = 1时,它要求输入名称,并要求输入年份。简而言之,它不允许用户在int年中i = 0之后输入数据。

/* Write a program to take input name roll number and year of joining of 5 students and making a function which prints name of only those who have joined in the particular year mentioned by the user*/
#include<stdio.h>
#include<conio.h>
struct student
{
   char name[50];
   int year;

}
a[5];

void func ( void );
void main ( void )
{
   int i;
   for ( i = 0; i < 5; i++ )
   {
      printf ( "Enter name %d\n", i + 1 );
      gets ( a[i].name );
      puts ( "Enter year" );

      scanf ( "%d", &a[i].year );
   }
   func(); 
   getch();
}
void func ( void )
{
   int i;
   int yearr;
   printf ( "Enter a year:" );
   scanf ( "%d", &yearr );
   for ( i = 0; i < 5; i++ )
   {
      if ( yearr == a[i].year )
      {
         printf ( "%s", a[i].name );
      }// if ends

   }//for ends
}// func ends

3 个答案:

答案 0 :(得分:3)

除了gets的代码臭味(USE fgets。请等。现在,虽然您还没有正确学习错误。),以及您输出的视频(A {{1}这里和那里会有奇迹),看起来它可以工作。假设您希望从用户那里获得5个名字和年份,那么请求一年搜索,并列出年份匹配的所有学生姓名。 (如果这不是你想要的,那么逻辑甚至不像你想象的那么清晰。)

就个人而言,我不会混合\nscanf(是的,我说fgets。使用它。),所以我不确定这样做的问题。无论如何,我不是fgets的粉丝,所以我可能有偏见。

答案 1 :(得分:1)

我认为您的问题与此问题有关: Input in C. Scanf before gets. Problem.

尝试:

scanf("%d\n", &yearr);

答案 2 :(得分:1)

在使用fflush(stdin)fflushall()进行输入之前清除输入缓冲区。您修改后的代码如下所示。

/* Write a program to take input name roll number and year of joining of 5 students and making a function which prints name of only those who have joined in the particular year mentioned by the user*/
    #include<stdio.h>
    #include<conio.h>
    struct student
    {
       char name[50];
       int year;

    }
    a[5];

    void func ( void );
    void main ( void )
    {
       int i;
       for ( i = 0; i < 5; i++ )
       {
          printf ( "Enter name %d\n", i + 1 );
          fflush(stdin);
          gets ( a[i].name );
          puts ( "Enter year" );

          scanf ( "%d", &a[i].year );
       }
       func(); 
       getch();
    }
    void func ( void )
    {
       int i;
       int yearr;
       printf ( "Enter a year:" );
       scanf ( "%d", &yearr );
       for ( i = 0; i < 5; i++ )
       {
          if ( yearr == a[i].year )
          {
             printf ( "%s", a[i].name );
          }// if ends

       }//for ends
    }// func ends