2016-07-25 102 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