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...

有帮助吗?

解决方案

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.

其他提示

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) .

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top