2017-07-14 3 views
1

私は以下の問題を抱えています..: 私は自分のコードを実行しますが、著者の数は正しく読みますが、あなたは名の文字列/ char型の値が正しく表示されますが、日付の整数値だけでランダムな数字です見ることができるように...構造体を持つ動的配列の変数からランダムな値を返します

typedef struct{ 
    int year; 
    int month; 
    int day; 
}Date; 

typedef struct{ 
    char lastName[30]; 
    char firstName[30]; 
    Date birthday; 
}Person; 

int main(){ 

    //assigning memory dynamically to array of authors 
    int n; 
    printf("How many authors should be added to the archive?\n"); 
    scanf("%i", &n); 

    //array of authors 
    Person* authors = (Person*) calloc(n, sizeof(Person)); 

    //reading authors 
    int i; 
    for(i = 0; i < n; i++){ 
     addAuthor(authors, i); 
    } 

    //writing authors to screen 
    for(i = 0; i < n; i++){ 
     printAuthor(authors[i]); 
    } 

    free(authors); 
    return 0; 
} 

Date inputDate(){ 
    Date d; 
    printf("Input year: "); 
    scanf(" %s", &d.year); 
    printf("Input month: "); 
    scanf(" %s", &d.month); 
    printf("Input day: "); 
    scanf(" %s", &d.day); 
    return d; 
} 

Person inputAuthor(){ 
    Person p; 
    printf("\nInput last name: "); 
    scanf(" %s", &p.lastName); 
    printf("Input last name: "); 
    scanf(" %s", &p.firstName); 
    p.birthday = inputDate(); 
    return p; 
} 

void printAuthor(Person p){ 
    printf("\n%s, %s born %i.%i.%i", p.lastName, p.firstName, p.birthday.day, p.birthday.month, p.birthday.year); 
} 

void addAuthor(Person* p, unsigned u){ 
    p[u] = inputAuthor(); 
} 

Example console log

:私は(例えば)これを取得する画面

+1

'%s'は整数ではなく文字列を読み取るためのものです。 –

+0

2nd 'printf("入力姓名: ");' - > 'printf("入力名: ");' – BLUEPIXY

答えて

1

あなたは、誤った日付を読み取るRE:

printf("Input year: "); 
scanf(" %s", &d.year); 
printf("Input month: "); 
scanf(" %s", &d.month); 
printf("Input day: "); 
scanf(" %s", &d.day); 

これらのフィールドは、タイプintであるが、%s形式指定子はchar配列へのポインタを期待します。不正な書式指定子を使用すると、undefined behaviorが呼び出されます。

整数値を読み取るには、%dフォーマット指定子を使用します。

printf("Input year: "); 
scanf("%d", &d.year); 
printf("Input month: "); 
scanf("%d", &d.month); 
printf("Input day: "); 
scanf("%d", &d.day); 
+0

ありがとう!こんなに小さなミスが私に何時間も見せてくれる... –

関連する問題