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

// プロトタイプ
void EnCode( char *, int );
void DeCode( char *, int );


//****************************************************************************//
//　◎メイン関数　
//****************************************************************************//
int main()
{
	char *str = NULL;
	int shift;

	// 
	printf( "文字列を入力してください:\n" );
	for ( int size = 1;  ; size++ ){
		str = (char*)realloc(str, sizeof(char)*size);					// 動的サイズ変更
		if ( str == NULL ) exit(1);							// メモリ確保失敗
		str[size-1] = getchar();							// 入力データ取得
		if ( str[size-1] == '\n' ) break;						// 終了文字発見
	}
	printf( "シフト値を入力してください(1～25):\n" );
	scanf( "%d", &shift );
	
	// 
	EnCode( str, shift );
	printf( "暗号文 → " );
	for ( int loop = 0; str[loop] != '\n'; loop++ ) putchar(str[loop]);
	printf("\n");															
	DeCode( str, shift );
	printf( "複合文 → " );
	for ( int loop = 0; str[loop] != '\n'; loop++ ) putchar(str[loop]);

	free(str);															
	//getch();															
	return 0;
}


//-----------------------------------------------------------------------------//
// 関数名　：　EnCode()
// 機能概要：　暗号化処理
//-----------------------------------------------------------------------------//
void EnCode( char *str, int num )
{
	for ( ; *str != '\n'; str++ ){ 
		if	( 'A' <= *str && *str <= 'Z' ) *str = (*str-'A' + num) % 26 + 'A';	// 26 = ('Z'-'A'+1)
		else if ( 'a' <= *str && *str <= 'z' ) *str = (*str-'a' + num) % 26 + 'a';	// 26 = ('z'-'a'+1)
		else if ( ' ' <= *str && *str <= '9' ) *str = (*str-' ' + num) % 26 + ' ';	// 26 = ('9'-' '+1)
	}
}


//-----------------------------------------------------------------------------//
// 関数名　：　DeCode()
// 機能概要：　複合化処理
//-----------------------------------------------------------------------------//
void DeCode( char *str, int num )
{
	for ( ; *str != '\n'; str++ ){
		if	( 'A' <= *str && *str <= 'Z' ) *str = (*str-'A' + 26-num) % 26 + 'A';
		else if ( 'a' <= *str && *str <= 'z' ) *str = (*str-'a' + 26-num) % 26 + 'a';
		else if ( ' ' <= *str && *str <= '9' ) *str = (*str-' ' + 26-num) % 26 + ' ';
	}
}
