Sai Sandeep Chenna
Sai Sandeep Chenna

Reputation: 1

Problem with the structures and loops in c programming

I wanted to create a program in c that reads the student name, roll number, marks of 3 subjects. when I run the program it is showing no errors, but the problem is whenever I try to input information it is taking only 2 inputs. Anyone please check the program and state the error in my program.

#include <stdio.h>
struct student 
{
  char sname[20];
  int srollno;
  int smarks[3];
};

int main ()
{
  struct student e[3];
  int i,j;
  for (i=0;i<=2;i++)
  {
    scanf ("%s",e[i].sname);
    scanf ("%d",e[i].srollno);
    for (j=0;j<=2;j++)
    {
        scanf ("%d",e[i].smarks[j]);
    }
  }
}

it is taking only two inputs.

Upvotes: 0

Views: 529

Answers (2)

EsmaeelE
EsmaeelE

Reputation: 2688

I perform some little change on your code. This is working version of code.

Code

#include <stdio.h>
struct student 
{
  char sname[20];
  int srollno;
  int smarks[3];
};

int main ()
{
  struct student e[3];
  int i,j;
  for (i=0;i<=2;i++)
  {

    printf("Name: ");
    scanf("%s", e[i].sname);
    printf("roolNumber: ");   
    scanf("%d", &e[i].srollno);
    
    
    for (j=0;j<=2;j++)
    {
    
        printf("Mark %d: ",j);
        scanf("%d", &e[i].smarks[j]);
    }
  }

  printf("\n\nprinting \n\n");
  for (i=0;i<=2;i++)
  {

    printf("Name: %s\n", e[i].sname);
    printf("roolNumber: %d\n", e[i].srollno);

    for (j=0;j<=2;j++)
    {
        printf("Mark: %d\n", e[i].smarks[j]);

    }
    printf("\n");
  }
}

Compile and Run

gcc -Wall source.c -o source

./source

I suggest to use printf() before try to scanf(), this makes User Interface better.

scanf() char array don't need & (address) operator. see this

char str[10];
scanf("%s", str);
printf("%s\n", str);

Work exactly like

char str[10];
scanf("%s", &str[0]);
printf("%s\n", str);

Because str is pointer to its first elementstr[0]. As stated in link we can write printf("%d\n", str==&str[0]); and always the result is one that show str and &str[0] are identical.

Upvotes: 1

yupe
yupe

Reputation: 127

you have some problem in your scanf. Try this:

scanf("%s",&e[i].sname);

Upvotes: 1

Related Questions