Domanda

My problem looks very simple and im so sorry for asking but what its wrong with this code?! why is just skipping the name part?!

#include <stdio.h>
#include <conio.h>
#include <string.h>
#define nl printf("\n")

struct date{int day,month,year;};
struct student{long int id;char name[30];struct date birthday;};

int main()
{
    struct student temp;
    nl;nl;printf("ID no:");scanf("%ld",&temp.id);nl;
    printf("Student name:");
    gets(temp.name);
    nl;nl;
    printf("Student birthday year:19");scanf("%d",&temp.birthday.year);nl;
    printf("Student birthday month");scanf("%d",&temp.birthday.month);nl;
    printf("Student birthday day");scanf("%d",&temp.birthday.day);nl;
    getch();        //for pause
    return 0;
}

Is there anything wrong about gets function?! cause i don't want to use scanf("%s",) because of space thing...

È stato utile?

Soluzione

This is because it reads the \n character left behind by scanf. Use

int ch;
while((ch = getchar()) != '\n' && ch != EOF);  

to consume \n.

And better not to use gets as it fails in array bound check. Use fgets instead.

Altri suggerimenti

As said by haccks, you should not use gets(), but if you really want to use it in your code use gets() before the id no. ie after the struct student temp; line, and if you want to print it then simply puts(temp.name) .

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top