2016-07-25 105 views
0

我已經使用結構方法編寫了簡單的代碼,並且在該代碼中,我將字符串(名稱)用作3個學生的for循環的輸入。對於第一次迭代for循環中的每一行工作,因爲它應該是......但問題出現在第二次迭代......在第二次迭代scanf跳過字符串(名稱)的輸入...scanf函數在C編程中跳過for循環的輸入

我的代碼是如下:

#include<stdio.h> 

struct student_data 
{ 
    char name[5]; 
    int dsd; 
    int dic; 
    int total; 
}; 

void main() 
{ 
    struct student_data s[3]; 


    int i; 

    for(i = 0;i<3;i++) 
    { 
     printf("Enter Name of Student\n"); 
     scanf("%[^\n]",s[i].name);   // Problem occures here in  
             // second iteration 

     printf("\nEnter marks of DSD\n"); 
     scanf("%d",&s[i].dsd); 

     printf("Enter marks of DIC\n"); 
     scanf("%d",&s[i].dic); 


     s[i].total = s[i].dsd+s[i].dic;  

    } 

    printf("%-10s %7s %7s %7s\n ","Name","DSD","DIC","Total"); 
    for(i=0;i<3;i++) 
    { 

     printf("%-10s %5d %6d  %6d\n",s[i].name,s[i].dsd,s[i].dic,s[i].total); 
} 

}

+1

無論如何,您正在使用'scanf()'錯誤。如果你不想讀未初始化的內存,你必須檢查返回值。而你不想,因爲它是未定義的行爲。 'scanf()'的問題在於它很難在現實生活中使用它,這就是爲什麼它很少被使用,但它是每個人都瞭解的第一件事[tag:c]。請閱讀'scanf()'的文檔,你可能會發現自己爲什麼不能正常工作,爲什麼它很難。 –

+0

錯誤的'scanf()'。使用'scanf(「%4 [^ \ n]」,s [i] .name);'代替。 –

+0

@AbhishekTandon如果我們使用'scanf(「%4 [^ \ n]」,s [i] .name);'。我們可以提供超過4個字符的名字嗎? –

回答

0

與您的代碼的主要問題是,你所定義的student_data s[2]是尺寸兩者的陣列,但在循環中,你是循環for (i=0; i<3; i++)有效期爲數組大小3.這個小的修改將工作正常:

int main() 
{ 
struct student_data s[2]; // array of size 2 


int i; 

for(i=0; i<2; i++)  // i will have values 0 and 1 which is 2 (same as size of your array) 
{ 
    printf("Enter Name of Student\n"); 
    scanf("%s", s[i].name); 

    printf("\nEnter marks of DSD\n"); 
    scanf("%d", &s[i].dsd); 

    printf("Enter marks of DIC\n"); 
    scanf("%d", &s[i].dic); 

    s[i].total = s[i].dsd+s[i].dic; 

} 

    printf("%-10s %7s %7s %7s\n ","Name","DSD","DIC","Total"); 

    for(i=0; i<2; i++) // same mistake was repeated here 
    { 
     printf("%-10s %5d %6d  %6d\n",s[i].name,s[i].dsd,s[i].dic,s[i].total); 
    } 
return 0; 
} 
+0

thnx你的解決方案工作....但我仍想知道爲什麼%[^ \ n]跳過來自用戶的輸入? – rushank27

+0

@ rushank27看看這篇文章:http://stackoverflow.com/questions/6083045/scanf-n-skips-the-2nd-input-but-n-does-not-why – reshad