2014-01-06 2 views
1

내 문제는 매우 간단하고 묻어서 미안하지만이 코드가 잘못된 것은 무엇입니까?! 왜 그냥 이름 부분을 건너 뛰는거야?!왜 "gets"함수가 실제로 문자열을 얻을 수 없습니까?

#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()를 사용하면 안되지만 코드에서 실제로 사용하려면 id 번호 앞에 gets()을 사용하십시오. 예 : struct student temp; 줄 다음에 인쇄하려는 경우 간단히 puts(temp.name)입니다.