Menu
CoddyTech

連絡先にデータを入力する関数

CoddyのCジャーニー「論理と制御フロー」セクションの一部。レッスン 52/63。

challenge icon

チャレンジ

簡単

前のレッスンで作成した連絡先作成関数を基に、ユーザー入力で連絡先を設定する関数を作成しましょう。プログラムは次のようにします。

  1. 前のレッスンと同じ Contact 構造体定義を使い、次のメンバーを含めます。
    • サイズ50の文字配列 name
    • サイズ20の文字配列 phone
    • サイズ40の文字配列 email
    • 整数 age
  2. 前のレッスンと同じ createContact 関数を使いますが、printf の行を削除して、Contact created successfully を出力しないようにします。関数は引き続き次の処理を行います。
    • Contact 構造体のメモリを動的に割り当てる
    • すべてのメンバーをデフォルト値で初期化する
    • 連絡先へのポインターを返す
  3. populateContact という名前の関数を作成します。この関数は次のようにします。
    • Contact 構造体へのポインターを引数として受け取る
    • 何も返さない(void)
    • ユーザーに入力を求め、次のデータをこの順序どおりに読み取る。
      • Enter name: を出力し、scanf("%s", contactPtr->name) を使って文字列を名前フィールドに読み取る
      • Enter phone: を出力し、scanf("%s", contactPtr->phone) を使って文字列を電話番号フィールドに読み取る
      • Enter email: を出力し、scanf("%s", contactPtr->email) を使って文字列をメールアドレスフィールドに読み取る
      • Enter age: を出力し、scanf("%d", &contactPtr->age) を使って整数を年齢フィールドに読み取る
    • すべての入力を読み取った後、データを検証する。
      • 年齢が0未満または120を超える場合、Invalid age entered を出力する
      • 電話番号の長さが10文字未満の場合(strlen() を使う)、Invalid phone number を出力する
      • すべての検証に合格した場合、Contact populated successfully を出力する
  4. main 関数では、次の処理を行います。
    • createContact 関数を使って連絡先を作成する
    • 連絡先の作成に成功したか確認する
    • populateContact 関数を呼び出して連絡先データを入力する
    • 入力後、次の形式どおりにアロー演算子を使って連絡先情報を表示する。
      • Contact Information:
      • Name: [name]
      • Phone: [phone]
      • Email: [email]
      • Age: [age]
    • 動的に割り当てたメモリを解放する
    • Contact deleted successfully を出力する

この課題では、ポインターを通じて構造体のデータを変更する関数の作成方法を学びます。populateContact 関数は連絡先へのポインターを受け取り、アロー演算子を使って元の構造体のメンバーを直接変更します。ユーザー入力の処理、データの検証、関数の引数を通じた動的割り当て構造体の操作を練習します。

自分で試してみよう

#include <stdio.h>
#include <stdlib.h>

struct Contact {
    char name[50];
    char phone[20];
    char email[40];
    int age;
};

struct Contact* createContact() {
    struct Contact* contactPtr = (struct Contact*)malloc(sizeof(struct Contact));
    
    if (contactPtr == NULL) {
        printf("Memory allocation failed\n");
        return NULL;
    }
    
    printf("Contact created successfully\n");
    
    contactPtr->name[0] = '\0';
    contactPtr->phone[0] = '\0';
    contactPtr->email[0] = '\0';
    contactPtr->age = 0;
    
    return contactPtr;
}

int main() {
    struct Contact* newContact;
    
    newContact = createContact();
    
    if (newContact == NULL) {
        printf("Failed to create contact\n");
        return 1;
    }
    
    printf("Contact initialized with default values\n");
    
    printf("Default Contact Values:\n");
    printf("Name: %s\n", newContact->name);
    printf("Phone: %s\n", newContact->phone);
    printf("Email: %s\n", newContact->email);
    printf("Age: %d\n", newContact->age);
    
    free(newContact);
    printf("Memory freed successfully\n");
    
    return 0;
}

論理と制御フローのすべてのレッスン

自分で練習してみよう: Cオンラインコンパイラ