0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

input関数,output関数

Last updated at Posted at 2020-04-17

#問題
3人分の名前、生年月日のデータが入った構造体を定義し,それをinput関数によって読み込み,output関数によって表示する.
#試行錯誤

関数, ポインタが分かってなかったころの一番最初の回答(ひどい間違い):

#include<stdio.h>

#define NAME_LEN 20

struct birthday
{
    char name[NAME_LEN];
    int year;
    int month;
    int day;
};

void input(char name, int year, int month, int day)
{
    char birth[4];
    birth = {name, year, month, day};
}

void output(char name2)
{
    printf("%s", name2);
}

int main(void)
{
    struct birthday takao = {Takao, 1998, 7, 5};
    struct birthday kyoko = {Kyoko, 1996, 8, 1};
    struct birthday yuta = {Yuta, 1997, 3, 28};

    puts("【入力】");
    input(takao.name, takao.year, takao.month, takao.day);
    input(kyoko.name, kyoko.year, kyoko.month, kyoko.day);
    input(yuta.name, yuta.year, yuta.month, yuta.day);
    
    puts("【出力】");
    output(input(takao.name, takao.year, takao.month, takao.day));
    output(input(kyoko.name, kyoko.year, kyoko.month, kyoko.day));
    output(input(yuta.name, yuta.year, yuta.month, yuta.day));

    return 0;    
}

#正解

#include<stdio.h>

typedef struct birthday
{
    /* data */
    char name[20];
    int year;
    int month;
    int day;
}Birthday;

void input(Birthday *);
void output(Birthday *);

int main(void){

    Birthday p[3];
    input(p);
    output(p);
    return 0;
}

void input(Birthday *man){
    int i;
    for ( i = 0; i < 3; i++)
    {
        /* code */
        scanf("%s\n ", man->name);
        scanf("%d %d %d", &man->year, &man->month, &man->day); 
        man++;
    }
}

void output(Birthday *man){
    int i;
    for ( i = 0; i < 3; i++)
    {
        /* code */
        printf("%-8s ", man->name);
        printf("%5d %2d %2d \n", man->year, man->month, man->day); 
        man++;
    }
}

#感想
・もっと言い書き方があるだろうと思う.
man++がC言語っぽい.ポインタについてはまた詳しく学んだとき書き残したい.
void input(Birthday *);
void output(Birthday *);など構造体を宣言してしまえば,関数の引数としてintなど型をまた書かなくても良い.Birthday *のみで良いことが分かる.というかBirthdayのなかにchar name[20] int year int month int dayが入っているというイメージ.
#おまけ
・カルテシアンはデカルトの名前からとられたと知って、なるほど、と思った。

0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?