LoginSignup
0
1

More than 3 years have passed since last update.

input,output関数を配列っぽい書き方にする

Posted at

概要

前回の記事にご指摘があり、配列っぽい書き方に直しました。

書き換える前

前回、以下のコードに対して

#include<stdio.h>

struct birthday
{
    /* data */
    char name[20];
    int year;
};

void input(struct birthday *);
void output(struct birthday *);

/*main function*/
int main(){
    struct birthday p[3]; /*重要*/
    input(p);
    output(p);
    return 0;
}

/*input function*/
void input (struct birthday *man)
{
    int i;
    printf("【入力】\n");
    for ( i = 0; i < 3; i++)
    {
        /* code */
        scanf("%s", man->name);
        scanf("%d", &man->year);
        man++;
    }
}

/*output function*/
void output(struct birthday *man)
{
    int i;
    printf("【出力】\n");
    for ( i = 0; i < 3; i++)
    {
        /* code */
        printf("%-8s", man->name);
        printf("%5d \n", man->year);
        man++;
    }
}

man++がポインタっぽい」とぼやいたところ

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

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

のように配列っぽく書いたらどうですか、とコメントがありました。ありがとうございました。

書き換えた後

数日たって復習のためにと以下のように書いたわけですが

#include<stdio.h>

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

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

/*main function*/
int main(void)
{
    Birthday man[3];
    input(man);
    output(man);
    return 0;
}

/*input function*/
void input(Birthday *man)
{
    int i;
    printf("【入力】\n");
    for ( i = 0; i < 3; i++)
    {
        /* code */
        scanf("%s", man[i].name);
        scanf("%d", &man[i].year);   
    }
}

/*output function*/
void output(Birthday *man)
{
    int i;
    printf("【出力】\n");
    for ( i = 0; i < 3; i++)
    {
        /* code */
        printf("%-8s", man[i].name);
        printf("%5d \n", man[i].year);
    }
}

後からinputoutputの引数をポインタを使って書いているのに気づき,配列の扱いにまだ慣れていないんだなと思いました。

結果の例

【入力】
yuga
1997
yuta
1998
huta
1996
【出力】
yuga     1997
yuta     1998
huta     1996

感想

mainの中のBirthday man[3]Birthday manと宣言しないこと。

0
1
0

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
1