カテゴリー
C C++

C++,Cで遊んでました。C++Builder入門、実習C言語

//#include <condefs>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
#pragma hdrstop

int main(int argc, char** argv)
{
	char buff[81];	//漢字大丈夫?
	ifstream infile;
	infile.open("readfile.cpp");
	if (!infile) return 0;
	while (!infile.eof()) {
		infile.getline(buff, sizeof(buff));
		cout << buff << endl;
	}

	infile.close();
	cout << endl << "Press any key to continue...";
	//getch();
	return 0;
}

上はC++Builder入門のサンプルコード。自分自身を表示します。

/*
Chotto.c multifile cat. procedures
Designed & created by N.Mita 1986/05/28 Copyright Core Dump Co,.Ltd.
*/

#include <stdio.h>
#include <ctype.h>

#include <stdlib.h>
#include <string.h>

#define CLS	cls()
//画面を消去する関数を呼ぶマクロ

#define MAXFILES 128	//このプログラムで扱えるファイル数の最大値256
#define MAXLINES 256	//このプログラムで扱える1行の文字数の最大値

static char file_name[MAXFILES][40];	//ファイル名を入れておくバッファ
FILE* fp;				//ファイル構造体へのポインタ

void cls()
{	//・・画面を消去する関数(どの処理系でも対応できるように、 25 行空行を送るだけにしてある)
	int i;
	for (i = 0; i < 25; ++i) printf("\n");
}

int open_file(fname) //ファイルをオープンする関数
char fname[];
{
	if (NULL == (fp = fopen(fname, "r")))
		return(0);
	else
		return(1);
}

void close_file()	//ファイルをクローズする関数
{
	fclose(fp);
}

void cat_file(line)	// ......... ファイルの内容を指定行数だけ表示する関数 
int line;		/* number of display lines*/
{
	int i, j;
	char line_buff[MAXLINES]; /* display line-buffer */

	for (i = 0; i < line; ++i) //....... 1行を処理するループ
	{
		if (NULL == fgets(line_buff, MAXLINES, fp)) 	// 1行を読み込み、エラーが起きた
		{						//かどうか判断する
			if (feof(fp)) break;			//ファイルの終わりならば for ループを抜ける
			if (ferror(fp))
			{
				printf(">>>>>>> Read-ERROR on FILE <<<<<<<\n");
				break;
			}
		}					//エラーであれば 処理を中断して終了

		for (j = 0; j < MAXLINES; ++j)		//......... ファイルから読み込んだ行を表示する
		{
			if ((int)NULL == line_buff[j]) break;	//読めない文字があった場合は、 .ピリオド
			if ((isspace(line_buff[j])) || (' ' <= line_buff[j]))
				putchar(line_buff[j]);
			else
				putchar('.');
		}
	}
}

int	disp_1file(fname, n)	//指定されたファイルを表示する関数
char fname[];			/* file-names for display */
int n;				/* number of display-lines */
{
	if (!open_file(fname))
	{
		printf("******* Cannot open file: %20s ******\n", fname);
		return(0);
	}
	else
	{
		printf("-------- FILE :  %20s --------\n", fname);
		cat_file(n);
		printf("\n\n");
	}
	close_file();
	return (1);
}

void	disp_file(m, n)			//・指定された複数ファイルを表示する関数 
int m;	/* Number of files */
int n;	/* Number of lines */
{
	int i; char dummy[40];

	for (i = 0; i < m; ++i)
	{
		disp_1file(&file_name[i][0], n);
		puts("Press return...........");
		gets(dummy);
	}
}

int input_file() 			//ファイル名の入力関数
{
	int i;

	CLS;

	for (i = 0; i < MAXFILES; ++i)
	{
		printf("%5d: FILE-NAME=", i + 1);
		gets(&file_name[i][0]);
		if (0 >= strlen(&file_name[i][0])) break;
	}
	return(i);
}

int input_line() 			//表示行数の入力関数
{
	char i_str[40];

	printf("        : LINES ?  = ");
	gets(i_str);

	return(atoi(i_str));
}

int main()	//・・・・・・メインの関数. できるだけシンプルになっていることが望ましい
{
	int i, j;

	if (0 >= (i = input_file()))			//.....・ファイル名の入力
	{
		printf("******* No files *******\n");
		exit(0);
	}
	else
	{
		if (0 >= (j = input_line()))	// 表示行数の入力
		{
			printf("******* No lines *******¥n");
			exit(0);
		}
		disp_file(i, j); 				//......... 実際の処理
	}


	printf("------- Complete. -------\n");	//作業終了の表示
	return 0;
}

上は三田典玄さんのサンプルコード。表示するファイル名をstaticで確保してます。

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <string.h>

using namespace std;
#pragma hdrstop

#define MAXFILES 5
#define MAXLINES 10

class FileNameArray
{
public:
	FileNameArray();
	~FileNameArray();
	char* getFname() { return fname; }
	void setFname(char* fn) { strcpy(fname, fn); }
private:
	char fname[40];
};

FileNameArray::FileNameArray()
{
	strcpy(fname, "end");
}

FileNameArray::~FileNameArray()
{
} 

int InputFileName(FileNameArray* fnm[]) {

	for (int i = 0; i < (MAXFILES - 1); i++) {
		char w[40];
		cout << i + 1 << " FileName: ";
		cin >> w;

		fnm[i]->setFname(w);
		if (strcmp(w, "end") == 0) {
			return -1;
		}
	}
	return 0;
}

void PrintFileName(FileNameArray* fnm[]) {
	for (int i = 0; i < MAXFILES - 1; i++) {
		cout << i + 1 << " :FileName: ";
		cout << fnm[i]->getFname() << endl;
		if (strcmp(fnm[i]->getFname(), "end") == 0)
			break;
	}
}

int PrintFileStop(FileNameArray* ptr[]) {
	char buff[81];

	for (int i = 0; i < MAXFILES - 1; i++) {
		ifstream infile;
		char w[40];
		int lcnt = 0;
		strcpy(w, ptr[i]->getFname());
		if (strcmp(w, "end") != 0) {
			infile.open(w);
			if (!infile) return -1;
			while (!infile.eof()) {
				infile.getline(buff, sizeof(buff));
				cout << buff << endl;
				lcnt++;
				if (lcnt > MAXLINES)
					break;
			}
		}
		else {
			infile.close();
			break;
		}
		infile.close();
	}
	return 0;
}

int main(int argc, char** argv)
{
	FileNameArray* fnab[MAXFILES];
	for (int i = 0; i < (MAXFILES - 1); i++)
		fnab[i] = new FileNameArray();

	InputFileName(fnab);

	char msg[40];
	(PrintFileStop(fnab) != 0) ? (strcpy(msg, "異常")) : (strcpy(msg, "正常"));
	cout << msg << "終了しました。";
	cout << endl << "Press any key to continue...";
	return 0;
}


上は見様見真似で弄り回した自分で書いたもの。ファイル名を入れておくところをclassで作って、mainに置いてます。それらはポインタの配列で、必要なルーティンへ渡します。PrintFileStopはほぼ、C++Builder入門のコードと同じです。

カテゴリー
C C++

C++Builder入門、サンプルプログラムAirport.makを動かす

//-------------------------------
#pragma once
//-------------------------------
#define AIRLINER 0
#define COMMUTER 1
#define PRIVATE 2
#define TAKINGOFF 0
#define CRUISING 1
#define LANDING 2
#define ONRAMP 3
#define MSG_CHANGE 0
#define MSG_TAKEOFF 1
#define MSG_LAND 2
#define MSG_REPORT 3

#include <stdio.h>
class Airplane {
  public:
	Airplane(const char* _name, int _type = AIRLINER);
	~Airplane();
	
	virtual int GetStatus(char* statusString);
	int GetStatus() {	return status;	}
	int Speed() { return speed; }
	int Heading() {	return heading;	}
	int Altitude() { return altitude;	}

	void ReportStatus();
	bool SendMessage(int msg, char* response, int spd = -1, int dir = -1, int alt = -1);
	char* name;
  protected:
	virtual void TakeOff(int dir);
	virtual void Land();
  private:
	int speed;
	int altitude;
	int heading;
	int status;
	int type;
	int ceiling;
};
#include <iostream> 
#include <stdio.h>
#include <cstring>
#pragma hdrstop

#include "airplane.h"
using namespace std;

//
// 初期化処理を行うコンストラクタ
//
Airplane::Airplane(const char* _name, int _type) :
	type(_type),
	status(ONRAMP),
	speed(0),
	altitude(0),
	heading(0)
{
	switch (type) {
	case AIRLINER: ceiling = 35000; break;
	case COMMUTER: ceiling = 20000; break;
	case PRIVATE: ceiling = 8000; break;
	//default: ceiling = 0;
	}
	name = new char[50];
	strcpy(name, _name);
}
//
// 終了処理を行うデストラクタ
//
Airplane::~Airplane()
{
	delete[] name;
}
//
// ユーザからメッセージを取得する
//
bool
Airplane::SendMessage(int msg, char* rtnMsg, int spd, int dir, int alt)
{
	// 不正なコマンドを検査する
	//
	strcpy(rtnMsg, " ");
	if (spd > 500) {
		char w[] = "Speed cannot be more than 500.";
		strcpy(rtnMsg, w);
		return false;
	}
	if (dir > 360) {
		char w[] = "Heading cannot be over 360 degrees.";
		strcpy(rtnMsg, w);
		return false;
	}
	if (alt < 100 && alt != -1) {
		char w[] = "I'd crash, bonehead!";
		strcpy(rtnMsg, w);
		return false;
	}
	if (alt > ceiling) {
		char w[] = "I can't go that high.";
		strcpy(rtnMsg, w);
		return false;
	}
	//
	// 送られたコマンドに基づいて各処理を実行する
	//
	switch (msg) {
	case MSG_TAKEOFF: {
		// すでに上空にいる場合は離陸できない
		if (status != ONRAMP) {
			char w[] = "I'm already in the air!";
			strcpy(rtnMsg, w);
			return false;
		}
		TakeOff(dir);
		break;
	}
	case MSG_CHANGE: {
		// 地上にいる場合は何も変更できない
		if (status == ONRAMP) {
			char w[] = "I'm on the ground";
			strcpy(rtnMsg, w);
			return false;
		}
		// 正の値が渡された場合のみ変更する
		if (spd != -1) speed = spd;
		if (dir != -1) heading = dir;
		if (alt != -1) altitude = alt;
		status = CRUISING;
		break;
	}
	case MSG_LAND: {
		if (status == ONRAMP) {
			char w[] = "I'm already on the ground.";
			strcpy(rtnMsg, w);
			return false;
		}
		Land();
		break;
	}
	case MSG_REPORT: ReportStatus();
	}
	//
	// すべてうまくいっている場合の標準的な応答
	//	
	char w[] = "Roger.";
	strcpy(rtnMsg, w);
	return true;
}
//
// 離陸处理
//
void
Airplane::TakeOff(int dir)
{
	heading = dir;
	status = TAKINGOFF;
}
//
//着陸処理
//
void
Airplane::Land()
{
	speed = heading = altitude = 0;
	status = ONRAMP;
}
//
// 飛行機のステータスを報告する文字列を作成する
//
int
Airplane::GetStatus(char* statusString)
{
	sprintf(statusString, "%s, Altitude: %d, Heading: %d, "
		"Speed: %d\n", name, altitude, heading, speed);
	return status;
}
//
// ステータス文字列を取得して、それを画面に表示する
//
void
Airplane::ReportStatus()
{
	char buffer[100];
	strcpy(buffer, " ");
	GetStatus(buffer);
	cout << endl <<buffer << endl;
}
//追加
//
// メッセージをセット
//
/*
void 
Airplane::SetMessage(char* msg) {
	strcpy_s(msg, strlen(msg), msg);
}
*/
#include <iostream>
#include <conio.h>
#pragma hdrstop

#include "airplane.h"
using namespace std;
int getInput(int max);
void getItems(int& speed, int& dir, int& alt);
int main(int argc, char** argv)
{
	char returnMsg[100];
	// Airpleのポインタ配列を用意し、 
	// 3つのAirplaneオブジェクトを作成する
	//
	Airplane* planes[3];
	planes[0] = new Airplane("TWA 1040");
	planes[1] = new Airplane("United Express 749", COMMUTER);
	planes[2] = new Airplane("Cessna 3238T", PRIVATE);
	//
	//ループ開始
	//
	do {
		int plane, message, speed, altitude, direction;
		speed = altitude = direction = -1;
		// メッセージを送るべき飛行機を取得する
		// 飛行機の一覧を表示し、 ユーザに1つ選択してもらう
		//
		cout << "Who do you want to send a message to?" << endl;
		cout << "0. Quit" << endl;
		for (int i = 0; i < 3; i++)
			cout << i + 1 << ". " << planes[i] -> name << endl;

		//
		// getInput ( ) 関数を呼び出して、 機体番号を取得する
		//
		plane = getInput(4);
		//
		// ユーザが項目を選択した場合はループを終了する
		//
		if (plane == -1) break;
		//
		// 飛行機の確認 47:
		//
		cout << endl << planes[plane]-> name << ", roger.";
		cout << endl << endl;
		//
		// 送信したいメッセージをユーザに選択してもらう 
		//
		cout << "What message do you want to send?" << endl;
		cout << endl << "0. Quit" << endl;;
		cout << "1. State Change" << endl;
		cout << "2. Take Off" << endl;
		cout << "3. Land" << endl;
		cout << "4. Report Status" << endl;
		message = getInput(5);
		//
		// ユーザが0を選択した場合はループを終了する
		//
		if (message == -1) break;
		//
		// ユーザが項目1を選択した場合は、
		// getItems ( ) 関数を呼び出して、
		// 新しい速度、機首角度、 高度を入力してもらう
		if (message == 0)
			getItems(speed, direction, altitude);
		//
		// 飛行機にメッセージを送信
		//
		bool goodMsg = planes[plane]->SendMessage(message, returnMsg, speed, direction, altitude);
		//
		//メッセージが不適切な場合
		//
		if (!goodMsg) cout << endl << "Unable to comply.";
		//
		// 飛行機の応答を表示
		//
		cout << endl << returnMsg << endl;
	} while (1);
	//
	// Airplainオブジェクトを削除する
	//
	for (int i = 0; i < 3; i++) delete planes[i];
}
int getInput(int max)
{
	int choice;

	do {
		choice = _getch();
		choice -= 49;

	} while (choice < -1 || choice > max);
	return choice;
}
void getItems(int& speed, int& dir, int& alt)
{
	cout << endl << "Enter new speed: ";
	//_getch();
	cin >> speed;
	cout << "Enter new heading: ";
	cin >> dir;
	cout << "Enter new altitude: ";
	cin >> alt;
	cout << endl;
}
カテゴリー
C C++

VS2019でC++とCの違いはどれ程あるんでしょうか?

ネタ本は、林晴比古さんの「C言語による実用アルゴリズム入門」です。

// ConsoleApplication2.cpp : このファイルには 'main' 関数が含まれています。プログラム実行の開始と終了がそこで行われます。
//

#include <iostream>

int gcd(int a, int b) {
    while (a != b) {
        if (a > b) a = a - b; else b = b - a;
    }
    return a;
}

int gcd2(int a, int b) {
    int w;
    while (b != 0) {
        w = a % b;
        a = b; b = w;
    }
    return a;
}

int main()
{
    int a = 128; int b = 72;
    printf("整数%d, 整数%d, の最大公約数=%d", a, b, gcd(a, b));
}

拡張子はcppになってますが、後はCのネタ本に出来るだけ近くしてます。

カテゴリー
C++

望洋先生のC++入門、線形リスト

lists.h

#pragma once

#include <stdio.h>
#include <string.h>

class Link {
	friend class List;
	Link* next;
	char item[20];

public:
	Link(const char* x = "") { 
		strcpy_s(item, x);
		next = NULL;
	}
	Link* Next(void) { return (next); }
	void LinkPrint(void) { printf("%s\n", item); }
};

class List {
protected:
	Link* first;
	Link* last;
public:
	List(void) { first = last = new Link; }
	~List() { Clear(); delete first; }
	List& Insert(const Link&);
	List& Append(const Link&);
	List& Delete(void);
	List& Remove(void);
	List& Clear(void);
	void Print(void);
};

list.cpp

#include <stdio.h>
#include "list.h"

//-----先頭に要素を追加-----
List& List::Insert(const Link& x)
{
	Link* ptr = first;
	first = new Link;
	*first = x;
	first->next = ptr;
	return (*this);
}

//-----末尾に要素を追加-----
List& List::Append(const Link& x)
{
	Link* ptr = last;
	*ptr = x;
	last = new Link;
	ptr->next = last;
	return (*this);
}

//----先頭要素を削除-----
List& List::Delete(void)
{
	if (first != last) {
		Link* ptr = first->next;
		delete first;
		first = ptr;
	}
	return (*this);
}

//-----末尾要素を削除-----
List& List::Remove(void)
{
	if (first != last) {
		Link* now = first;
		Link* pre = last;
		while (now->next != last) {
			pre = now;
			now = now->next;
		}
		pre->next = last;
		delete now;
	}
	return (*this);
}

//-----全要素を削除-----
List& List::Clear(void)
{
	Link* ptr = first;
	while (ptr != last) {
		Link* next = ptr->next;
		delete ptr;
		ptr = next;
	}
	first = last;
	return (*this);
}

//-----全要素を表示-----
void List::Print(void)
{
	puts("===== リ ス ト 一 覧=====");
	int no = 1;
	Link* ptr = first;
	while (ptr != last) {
		printf("%d : ", no++);
		ptr->LinkPrint();
		//putchar('\n');
		ptr = ptr->next;
	}
}

実行部分

#include "list.h"

int main()
// ConsoleApplication1.cpp : このファイルには 'main' 関数が含まれています。プログラム実行の開始と終了がそこで行われます。
//
{
	List L7;

	L7.Append(Link("柴田"));
	L7.Insert(Link("大賀"));
	L7.Append(Link("具島"));
	L7.Append(Link("増田"));
	L7.Append(Link("鈴木"));
	L7.Print();
	L7.Remove();
	L7.Print();
	L7.Insert(Link("伊藤"));
	L7.Print();
	L7.Delete();
	L7.Print();
	L7.Clear();
	L7.Print();
	return (0);
}
カテゴリー
C++

C++コード張り付けてみる

#pragma once

#include <stdio.h>
#include <string.h>

class Link {
	friend class List;
	Link* next;
	char item[20];

public:
	Link(const char* x = "") { 
		strcpy_s(item, x);
		next = NULL;
	}
	Link* Next(void) { return (next); }
	void LinkPrint(void) { printf("%s\n", item); }
};

class List {
protected:
	Link* first;
	Link* last;
public:
	List(void) { first = last = new Link; }
	~List() { Clear(); delete first; }
	List& Insert(const Link&);
	List& Append(const Link&);
	List& Delete(void);
	List& Remove(void);
	List& Clear(void);
	void Print(void);
};
カテゴリー
C++

C++コード張り付けてみる、utf-8ふぁいるだったら

#pragma once

#include <stdio.h>
#include <string.h>

class Link {
	friend class List;
	Link* next;
	char item[20];

public:
	Link(const char* x = "") { 
		strcpy_s(item, x);
		next = NULL;
	}
	Link* Next(void) { return (next); }
	void LinkPrint(void) { printf("%s\n", item); }
};

class List {
protected:
	Link* first;
	Link* last;
public:
	List(void) { first = last = new Link; }
	~List() { Clear(); delete first; }
	List& Insert(const Link&);
	List& Append(const Link&);
	List& Delete(void);
	List& Remove(void);
	List& Clear(void);
	void Print(void);
};
inserted by FC2 system