Mathew Koshy
Mathew Koshy

Reputation: 1

Scanf not behaving as expected

I am trying to use scanf() to input values to a structure using pointers.Can you help me to understand why my code is not working

This is my code:

#include<stdio.h>
struct student
{
   int no;
   float marks;
}st[2],*s;

main()
{
  printf("enter the values");
  for(s=st;s<st+2;s++)
  {
    scanf("%d%d",&s->no,&s->marks);
  }
  for(s=st;s<st+2;s++)
  {
    printff("%d\t%d\t",s->no,s->marks);
  }
}

in this code scanf is not working properly,it is taking only the first value

Upvotes: 0

Views: 64

Answers (3)

Kunal Saini
Kunal Saini

Reputation: 148

In the structure you have taken two variable one is int type and other is float type but while doing scanf(taking input) you are doing %d for float whereas it should be %f for float .This is a very minor mistake but you should try to avoid it on your own by just looking at your code carefully :)

Happy coding

Upvotes: 0

jayprakashstar
jayprakashstar

Reputation: 395

 #include<stdio.h>
     struct student
       {
      int no;
      float marks;
         }st[2],*s;


 main()
  {
 printf("enter the values");
 for(s=st;s<st+2;s++)
  {
 scanf("%d%f",&s->no,&s->marks);
  }
 for(s=st;s<st+2;s++)
   {
  printf("%d\t%f\t",s->no,s->marks);
    }
   }

U have to use %f for float

Upvotes: 0

Spikatrix
Spikatrix

Reputation: 20244

You are using the wrong format specifier. %d is used for ints while %f is used for floats. Use

scanf("%d%f",&s->no,&s->marks);

and

printf("%d\t%f\t",s->no,s->marks);

instead as s->marks is a float, not an int. Using the wrong format specifier leads to Undefined Behavior.

Upvotes: 2

Related Questions