1
2

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 5 years have passed since last update.

C言語 構造体とポインタ 実践を意識

Posted at

個人情報入力プログラムで構造体とポインタを練習する
ついでに以下のようなことも意識する
1)コードを実装していく順番
2)現場でよく見かける書き方

標準入力「氏名、年齢、住所、性別、電話番号、その他」
出力「テキスト形式」

今回は大枠のところまで

①扱うデータを決める
→構造体で作ろう。名前は文字列だからchar型の配列にしよう。など
②機能実現にどんな処理が必要か書き出す。
→今回の例では
1)コマンドプロンプト上で入力させる
2)入力したデータをファイルへ出力する
 が主な機能。
③汎用化できそうなものは関数に切り出す。
→main関数では関数呼び出しの枠部分だけ先に考えておく。(inputとoutputは決めておく)
④関数の中身を作っていく。
→大枠を作って詳細を作るのが王道みたい。
効率化のためにも肝になる最小限の機能をつくって、先に確認する。
似た処理、装飾の類の実装はあとからでもいい。

userinfo.c
# include "stdio.h"
# define NAME_BUFFER  ( 100 ) //define時の()は大切。仮に演算内で使用された場合、演算順序が意図しないものになることを防げる。  
# define PHONE_BUFFER (  20 )   

typedef unsigned char   uint8_t;  //型のサイズと符合の有り無しが分かる名前での型定義。
typedef unsigned short uint16_t;  //特に"int"は処理系によってサイズが異なるので"int"のまま使用してるのは見かけない。
typedef unsigned long  uint32_t;  //今回使わないけど

typedef struct UserInfo {			//構造体のtypedefは定番。structと毎回書く手間が省ける。
	uint8_t name[NAME_BUFFER];
	uint8_t phoneNumber[PHONE_BUFFER];
}st_UserInfo;

InputUserInfo(st_UserInfo* pst_UserInfo);
OutputToFile(st_UserInfo* pst_UserInfo);

int main(void) {
	st_UserInfo		*AclassP;
	st_UserInfo		Aclass;
	AclassP = &Aclass;
	InputUserInfo(AclassP);  //アドレス渡し ※参照渡しではない。参照渡しはC++のみ
	OutputToFile(AclassP);
	return 0;
}
InputUserInfo(st_UserInfo* pst_UserInfo) {	//p:ポインタ st:構造体 のような接頭語はよく見かける
	printf("名前を入力してください->");
	scanf_s("%s", pst_UserInfo->name,sizeof(pst_UserInfo->name));
}

OutputToFile(st_UserInfo* pst_UserInfo) {
	FILE* fp;   //ここら辺は常套句のようなものかな。
	fopen_s(&fp, "test1.txt", "w"); //調べ方と使い方が分かればOK。VCだとF1でヘルプ機能。
	fprintf_s(fp, "%s", pst_UserInfo->name);
	fclose(fp);
}
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?