Search code examples
cstringgets

why my "gets" function can't really get a string?


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


Solution

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