简体   繁体   中英

scanf function is skipping input in for loop in C Programming

I have write simple code using structure method and in that code I am taking string(name) as input using for loop for 3 students. For 1st iteration each line in for loop is working as it should be.... but problem comes on second iteration... in second iteration scanf is skipping input for string (name)...

My code is as below :

#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);
}  

}

The main problem with your code was that you defined the student_data s[2] which is a array of size two, but in the loop, you are looping for (i=0; i<3; i++) which is valid for an array of size 3. This small modifications will work fine:

 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM