2014-01-06 53 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)

相關問題