The scanf to get "name" skips itself when i execute it. What changes do I make inorder for it to no do that?

Advertisements
    #include <stdio.h>


    int b;
    int main()
    {
    int a, c;
    printf("Enter the number of students \n");
    scanf("%d", &a);
    
    struct studinfo{
        char name[50];
        int roll;
        float marks;
    };
    
    struct studinfo s[10];
    
    for(int i = 0; i <= a; i++)
    {
        printf("Enter the Name :\n");
        scanf("%[^\n]s", s[i].name);      //THIS ONE HERE
        printf("\n");
        printf("Enter the roll no. \n");
        scanf("%d", &s[i].roll);
        printf("\n");
        printf("Enter the marks\n");
        scanf("%f", &s[i].marks);
    }
    
    for(int i = 0; i<= a; i++)
    {
            printf("Name: %s\n", s[i].name);
            printf("Roll no: %d\n", s[i].roll);
            printf("Marks: %f", s[i].marks);
    }
    return 0;
    }

Works when I remove the scanf to enter number of students.

#include <stdio.h>


int b;
int main()
{
    int a, c;
    printf("Enter the number of students \n");

    
    struct studinfo{
        char name[50];
        int roll;
        float marks;
    };
    
    struct studinfo s[10];
    
    for(int i = 0; i <= a; i++)
    {
        printf("Enter the Name :\n");
        scanf("%[^\n]s", s[i].name);
        printf("\n");
        printf("Enter the roll no. \n");
        scanf("%d", &s[i].roll);
        printf("\n");
        printf("Enter the marks\n");
        scanf("%f", &s[i].marks);
    }
    
    for(int i = 0; i<= a; i++)
    {
            printf("Name: %s\n", s[i].name);
            printf("Roll no: %d\n", s[i].roll);
            printf("Marks: %f", s[i].marks);
    }
    return 0;
}

-> This happenes because the Scanf initially used takes everything except for ‘\n’ which is later is read by the next scanf which skips when it reads a ‘\n’.
-> Ive tried Fgets and gets too but still doesnt work.

The output im getting is;

after I enter the number of students, it just skips the scanf to enter the name and just executes scanf to enter the roll no.

>Solution :

For starters you should check that the value of a is not greater than 10 and the condition in for loops should look like

struct studinfo s[10];

for(int i = 0; i < a; i++)

As for your question then after this call of scanf

scanf("%d", &a);

the input buffer contains the new line character '\n' that corresponds to the pressed key Enter. So this call of scanf

scanf("%[^\n]s", s[i].name); 

reads an empty string. And there is redundant s character in the format string.

Instead you should write

scanf( " %49[^\n]", s[i].name );
       ^^^^^^^^^^ 

Pay attention to the leading space in the format string. It allows to skip white space characters.

Leave a ReplyCancel reply