2010-07-07 88 views
0

該程序的邏輯非常清晰,但它要求用戶輸入名稱。它第二次要求這個名字,即在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 

回答

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 
+0

對不起,我的程序有一些錯誤。請不要使用fflush(stdin)。有關更多信息,請參閱http://www.drpaulcarter.com/cs/common-c-errors.php。 – chanchal1987 2010-07-20 12:42:14

3

除了從gets代碼臭味(USE fgets請立即,當你」 RE仍然從錯誤中學習權利),以及你輸出的不可靠性(在這裏和那裏會產生奇蹟),它看起來可以工作。假設你想要它從用戶那裏得到5個名字和年份,然後要求一年搜索,並列出所有年齡匹配的學生姓名。 (如果這不是你想要的,邏輯甚至沒有接近明確的,因爲你認爲它是。)

就個人而言,我不會混合scanffgets(是的,我說:fgets。使用它。) ,所以我不確定這樣做的問題。無論如何,我不是粉絲scanf,所以我可能會有偏見。

+1

是的,永遠不會使用gets()。 – JeremyP 2010-07-07 11:06:59