2014-01-06 50 views
1

我的问题看起来很简单,我很抱歉问,但是这个代码有什么问题?为什么只是跳过名字部分?为什么我的“获取”函数不能真正得到一个字符串?

#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; 
} 

获取函数有什么不对吗?!因为我不想使用scanf("%s",)因为空间的原因...

+0

关于_“学生生日年:19”_,你写这本世纪了吗? – ryyker

+0

我是一个新的程序员抱歉没有知识... – amfad33

+4

'#define nl printf(“\ n”)'是可怕的C,并且不应该在程序中。 – abelenky

回答

1

这是因为它读取scanf留下的\n字符。使用

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

消耗\n

最好不要使用gets,因为它在数组绑定检查中失败。改为使用fgets

+1

*不要*使用'gets',正如解释过的。使用'fgets'并从'stdin'中读取。 'gets'是非常不安全的,因为它有许多问题:请参阅[这里的基本解释](http://c-faq.com/stdio/getsvsfgets.html)。 – SevenBits

0

正如haccks所说,你不应该使用gets(),但是如果你真的想在你的代码中使用它,使用gets()之前的id号。即在struct student temp;行之后,并且如果您想要打印它然后简单地puts(temp.name)

相关问题