336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

CPP aes128 cbc mode Encryption Decryption



AES


Encryption Block  : 

128 비트

192 비트 

256 비트


Mode :    

1. ECB ( Electric Code Book )

http://jo.centis1504.net/wp-content/uploads/2010/11/Encryption-ECB_MODE.swf




2. CBC ( Cipher Block Chaining )

http://jo.centis1504.net/wp-content/uploads/2010/11/Encryption-CBC_MODE.swf





3. OFB ( Output Feed Back )

http://jo.centis1504.net/wp-content/uploads/2010/11/Encryption-OFB_MODE.swf



4. CFB ( Cipher Feed Back )



5. CTR ( CounTeR )



모드별 설명은


관련 자료 참고 : http://www.parkjonghyuk.net/lecture/modernCrypto/lecturenote/chap04.pdf




구현에서는 CTR 모드로 구현하였다.






개발 환경 : Windows 7 64bit, VS 2013



최신버전으로 직접 빌드하시려면 아래의 링크를 참조하시기 바랍니다.


귀찮으신 분은 빌드된 버전을 사용합시다.


OpenSSL 빌드 : http://yokkohama.tistory.com/entry/OpenSSL-%EB%B9%8C%EB%93%9C%ED%95%98%EA%B8%B0-Visual-Studio-2010-%EB%98%90%EB%8A%94-libeay32dll-ssleay32dll-%EB%8B%A4%EC%9A%B4%EB%A1%9C%EB%93%9C



"openssl-1.0.1f_vc_no-idea no-mdc2 no-rc5_build.zip" 는 no-idea no-mdc2 no-rc5  로 빌드된, 특허문제가 해결 된 바이너리입니다.


openssl-1.0.1f_vc_no-idea no-mdc2 no-rc5_build.zip



압축 해제 후 파일을 프로젝트 폴더로 이동



프로젝트속성 > VC++ 디렉터리 > 디렉터리 설정 (포함 디렉터리, 라이브러리 디렉터리)






별도의 클래스를 만들어 사용 하였습니다.







#pragma once

#include 
#include 
#include 
#include 


struct ctr_state {
	unsigned char ivec[AES_BLOCK_SIZE];
	unsigned int num;
	unsigned char ecount[AES_BLOCK_SIZE];
};



class CAESCTR
{
public:
	AES_KEY key;
	int BYTES_SIZE = 1024;
	int KEY_SIZE = 128;
	unsigned char ckey[32];
	unsigned char iv[8];
	int init_ctr(struct ctr_state *state, const unsigned char iv[8]);
	void encrypt(unsigned char *indata, unsigned char *outdata, int bytes_read);
	void encrypt(CString& indata, CString& outdata, int bytes_read);
	CAESCTR();
	CAESCTR::CAESCTR(unsigned char* iv, unsigned char* ckey);
	~CAESCTR();
};







#include "stdafx.h"
#include "AESCTR.h"

int CAESCTR::init_ctr(struct ctr_state *state, const unsigned char iv[8]){
	state->num = 0;
	memset(state->ecount, 0, AES_BLOCK_SIZE);
	memset(state->ivec + 8, 0, 8);
	memcpy(state->ivec, iv, 8);

	return 0;
}
// encrypt twice  == decrypt

void CAESCTR::encrypt(unsigned char *indata, unsigned char *outdata, int bytes_read){

	int i = 0;
	int mod_len = 0;

	AES_set_encrypt_key(ckey, KEY_SIZE, &key);

	if (bytes_read < BYTES_SIZE){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, bytes_read, &key, state.ivec, state.ecount, &state.num);
		return;
	}
	// loop block size  = [ BYTES_SIZE ]
	for (i = BYTES_SIZE; i <= bytes_read; i += BYTES_SIZE){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, BYTES_SIZE, &key, state.ivec, state.ecount, &state.num);
		indata += BYTES_SIZE;
		outdata += BYTES_SIZE;
	}

	mod_len = bytes_read % BYTES_SIZE;
	if (mod_len != 0){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, mod_len, &key, state.ivec, state.ecount, &state.num);
	}
}

void CAESCTR::encrypt(CString& instr, CString& outstr, int bytes_read){

	int i = 0;
	int mod_len = 0;
	unsigned char *indata;
	unsigned char *outdata;

	indata = (unsigned char *)malloc(instr.GetLength() + 1);
	outdata = (unsigned char *)malloc(instr.GetLength() + 1);



	strncpy((char*)indata, (LPSTR)(LPCSTR)instr, instr.GetLength());
	indata[instr.GetLength()] = NULL;


	

	AES_set_encrypt_key(ckey, KEY_SIZE, &key);

	if (bytes_read < BYTES_SIZE){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, bytes_read, &key, state.ivec, state.ecount, &state.num);

		outdata[instr.GetLength()] = NULL;
		outstr = outdata;
		return;
	}
	// loop block size  = [ BYTES_SIZE ]
	for (i = BYTES_SIZE; i <= bytes_read; i += BYTES_SIZE){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, BYTES_SIZE, &key, state.ivec, state.ecount, &state.num);
		indata += BYTES_SIZE;
		outdata += BYTES_SIZE;
	}

	mod_len = bytes_read % BYTES_SIZE;
	if (mod_len != 0){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, mod_len, &key, state.ivec, state.ecount, &state.num);
	}
	outdata[instr.GetLength()] = NULL;
	outstr = outdata;
}

CAESCTR::CAESCTR()
{
	unsigned char temp_iv[8] = { 0x66, 0x61, 0x63, 0x65, 0x73, 0x65, 0x61, 0x00 };
	memcpy(iv, temp_iv, 8);

	unsigned char temp_ckey[32] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
		0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
		0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34,
		0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56 }; // 32bytes = AES256, 16bytes = AES128
	memcpy(ckey, temp_ckey, 32);
}

CAESCTR::CAESCTR(unsigned char* iv, unsigned char* ckey)
{
	memcpy(this->iv, iv, 8);
	memcpy(this->ckey, ckey, 32);
}

CAESCTR::~CAESCTR()
{
}






그리고, 프로젝트 속성에서


구성 속성 > 문자 집합 > 설정 안 함


으로 하여서 사용하였습니다.



사용예시










void CPasswordEncoderDlg::OnEnChangeEdit1()
{
	// TODO:  RICHEDIT 컨트롤인 경우, 이 컨트롤은
	// CDialogEx::OnInitDialog() 함수를 재지정 
	//하고 마스크에 OR 연산하여 설정된 ENM_CHANGE 플래그를 지정하여 CRichEditCtrl().SetEventMask()를 호출하지 않으면
	// 이 알림 메시지를 보내지 않습니다.

	// TODO:  여기에 컨트롤 알림 처리기 코드를 추가합니다.
	CAESCTR m_AESCTR;

	CString editText;
	m_Edit1.GetWindowTextA(editText);
		
	int editTextLength = editText.GetLength();

	unsigned char* editTextCharSeq;
	editTextCharSeq = (unsigned char *)malloc(editTextLength+1);

	strncpy((char*)editTextCharSeq, (LPSTR)(LPCSTR)editText, editTextLength);
	editTextCharSeq[editTextLength] = NULL;

	unsigned char* outTextCharSeq;
	outTextCharSeq = (unsigned char *)malloc(editTextLength + 1);

	m_AESCTR.encrypt(editTextCharSeq, outTextCharSeq, editTextLength);
	outTextCharSeq[editTextLength] = NULL;
	
	editText = outTextCharSeq;
	m_Edit2.SetWindowTextA(editText);
	
	m_AESCTR.encrypt(editText, editText, editTextLength);

	m_Edit3.SetWindowTextA(editText);

	free(editTextCharSeq);
	free(outTextCharSeq);
}










'Programming > C,CPP,CS' 카테고리의 다른 글

openssl AES encrypt (AES_ctr128_encrypt)  (0) 2016.09.19
openssl AES Mode : ECB, CBC, CFB, OFB, CTR  (0) 2016.09.05
CDateTimeCtrl 사용법  (0) 2016.08.25
Apache License, Version 2.0  (0) 2016.08.22
Log4cxx ChainSaw Appender  (0) 2016.08.22

MFC CTextProgressCtrl

Programming/MFC 2016. 8. 17. 15:50 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

MFC CTextProgressCtrl




코드만 가져다가 ProgressCtrl 을 TextProgressCtrl 로 변환 시켜서 사용할 수 있다.






MemDC 가 필요한데 VS2010 이상 버전에서는


CGridCtrl 을 참고하여 추가 설정이 필요하다.

(시스템에 존재하는 MemDC 클래스와 중복되기 때문)












http://www.codeproject.com/Articles/80/Progress-Control-with-Text


Progress Control with Text

























This is a simple CProgressCtrl derived class that allows text to be displayed on top of the progress bar in much the same way as many "Setup" programs display the progress of long operations.

The control is extremely simple and allows the same operations as a standard CProgressCtrl, as well as: 

void SetShowText(BOOL bShow);Specifies whether or not the text for the control will be displayed during updates
COLORREF SetBarColor(COLORREF crBarClr = CLR_DEFAULT);Specifies the colour of the progress control bar, and returns the previous colour. If the colour is set asCLR_DEFAULT then the Windows default colour is used.
COLORREF GetBarColor();Returns the colour of the progress control bar, orCLR_DEFAULT if the default Windows colours are being used.
COLORREF SetBarBkColor(COLORREF crBarClr = CLR_DEFAULT);Specifies the colour for the control's background, and returns the previous background colour. If the colour is set as CLR_DEFAULT then the Windows default colour is used.
COLORREF GetBarBkColor();Returns the colour of the control's background, orCLR_DEFAULT if the default Windows colours are being used.
COLORREF SetTextColor(COLORREF crBarClr = CLR_DEFAULT);Specifies the colour of the text, and returns the previous colour. If the colour is set as CLR_DEFAULT then the Windows default colour is used.
COLORREF GetTextColor();Returns the colour of the text, or CLR_DEFAULT if the default Windows colours are being used.
COLORREF SetTextBkColor(COLORREF crBarClr = CLR_DEFAULT);Specifies the background colour of the text, and returns the previous background colour. If the colour is set asCLR_DEFAULT then the Windows default colour is used.
COLORREF GetTextBkColor();Returns the background colour of the text, orCLR_DEFAULT if the default Windows colours are being used.
BOOL SetShowPercent(BOOL bShow)Sets whether or not to show the percentage value of the bar, and returns the old value
DWORD AlignText(DWORD dwAlignment = DT_CENTER)Sets the text alignment and returns the old value
BOOL SetMarquee(BOOL bOn, UINT uMsecBetweenUpdate)Sets whether or not the progress control is in marquee mode, as well as the interval in milliseconds between steps of the marquee block
int SetMarqueeOptions(int nBarSize)Sets the size of the marquee as a percentage of the total control width

To set the text to be displayed use the standard CWnd::SetWindowText. If you call SetShowText(TRUE) but do not specify any window text using CWnd::SetWindowText, then the percentage fraction of progress will be displayed as default.

To use the control, just include a CProgressCtrl in your app as per usual (either dynamically or by using a dialog template) and change the variable type from CProgressCtrl to CTextProgressCtrl. (Make sure you include TextProgressCtrl.h)

At present the progress is only displayed as a smooth bar, and colours are strictly windows default colours. (These may be changed in the future versions.)

Acknowledgements
Thanks to Keith Rule for his CMemDC class.

Updates

Pete Arends went to town on the code. His updates:

  1. Set the font used to the parent window font
  2. Added SetTextColour() and GetTextColour() functions
  3. Added a bunch of message handlers, so the control now responds to the standard progress bar PBM_*messages. It is now possible to control the text progress control by sending messages to it. (works great from a worker thread).
  4. Added 2 new messages PBM_SETSHOWTEXT and PBM_SETTEXTCOLOR.
  5. Added an OnGetPos() handler. The function GetPos() now works!!

Thanks Pete!

3 Jan 05: Kriz has also extended the code with two basic methods that allow switching between the three alignment styles LEFTCENTER and RIGHT - even on the fly if that's needed.

Changes to the code

  • Created a protected DWORD member m_dwTextStyle
  • Disabled all dwTextStyle variables in OnPaint or replaced them by
    m_dwTextStyle
  • Added two methods called AlignText and AlignTextInvalidate

Syntax

BOOL AlignText(DWORD aligment = DT_CENTER);
BOOL AlignTextInvalidate(DWORD aligment = DT_CENTER);

Params/Return:

"alignment" can be DT_LEFTDT_CENTER (default) or DT_RIGHT. Using the invalidating version forces the control to repaint itself automatically. Both methods will return FALSE if a wrong alignment flag was given, otherwise they will return TRUE to the caller.

Thank you Kriz!

I've also updated the code so it compiles in VC7.X.

9 mar 06: Tony Bommarito has updated the code to include more settings for colours, made corrections to vertical text mode and added a new marquee mode.

26 Feb 07: Tony Mommarito has provided further updates:

  • Fixed bug where outside edge of progress bar wasn't drawn on XP when using an application manifest.
  • Added complete turn-off of marquee mode in a slightly different manner than that suggested in Robert Pickford message.
  • Fixed Unicode compile bug reported in dev75040 message.
  • Added three SLN and VCPROJ file sets; one each for VS2002, VS2003 and VS2005. By removing the VS… extension from the proper set, any of the three IDEs can be used.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)







336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

성동구 인근 지역 프로그래밍 과외 합니다.


지역 : 서울 성동구 인근


종목 : 프로그래밍, 정보올림피아드, CCNA, CCNP


경력 : 지도학생) 2013 초등부 정보올림피아드 전국대회 은상 수상

        지도학생) 정보올림피아드 본선 진출 다수


         전) 서울 서울특별시립종합직업전문학교 외부강사

         전) 천안 그린컴퓨터학원 프로그래밍 강사

         전) 한국기술교육대학교 대학원 컴퓨터공학부 박사과정 수료

         전) 청주 그린컴퓨터학원 프로그래밍 강사

         전) 아산소재 대학교 시간강사

         전) 천안소재 대학교 시간강사



         현) 한국기술교육대학교 평생능력개발 이러닝 운영강사

         현) IT기업 연구소 재직중




자세한 문의는


tansanc23@gmail.com 으로 문의해 주세요.

공일공-구구육이-일사일칠



336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

How to prevent MFC dialog closing on Enter and Escape keys?


There is an alternative to the previous answer, which is useful if you wish to still have an OK / Close button. If you override the PreTranslateMessage function, you can catch the use of VK_ESCAPE / VK_RETURN like so:



BOOL CMainDialog::PreTranslateMessage(MSG* pMsg)

{


if (pMsg->message == WM_KEYDOWN)

{

if (pMsg->wParam == VK_RETURN || pMsg->wParam == VK_ESCAPE)

{

return TRUE;                // Do not process further

}

}


return CDialogEx::PreTranslateMessage(pMsg);

}




이렇게 수정하여야 한다.




PreTranslateMessage 함수를 생성하는 방법은


1. Enter, ESC 키를 차단할 DialogClass 를 우클릭


2. [클래스 마법사] 를 켠다.


3. [가상 함수]


4. 가상 함수 탭에서 PreTranslateMessage 를 선택


5. [함수 추가]


6. 추가된 함수에


if (pMsg->message == WM_KEYDOWN)

{

if (pMsg->wParam == VK_RETURN || pMsg->wParam == VK_ESCAPE)

{

return TRUE;                // Do not process further

}

}


추가 작성




C++ Standard library has many containers

Programming/C,CPP,CS 2016. 7. 19. 10:37 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

C++ Standard library has many containers. Depending on situation you have to choose one which best suits your purpose. It is not possible for me to talk about each of them. But here is the chart that helps a lot (source):






C++ 스탠다드 라이브러리에 많은 컨테이너 들이 있다.
흔히 사용하는 List, Stack, Vector 뿐만 아니라 다양한 컨테이너들이 존재하는데, 그 컨테이너들을 언제 사용해야 할지를 FlowChart 를 따라가면서 쉽게 선택할 수 있다. 
















enter image description here




ATL,CPP,C# dll 배포

Programming/C,CPP,CS 2016. 5. 27. 10:56 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

ATL,CPP,C# dll 배포


dll 배포 관련 질문이 올라와서 저도 다시 한번 정리 할겸 올려 봅니다.







DLL reg 등록 방법


1. Visual Studio 기반으로 dll 을 만들어서


 디버그 옵션을 조절하여 


 html 이나 특정 app 을 실행하는 형태로 프로젝트 설정을 하였다면


 자동으로 Visual Studio 가 dll 을 해당 컴퓨터에 등록하게 됩니다.



배포를 하려면 배포할 컴퓨터에 일일이 Visual Studio 를 설치 할 수 없으므로


아래의 방법을 활용 합니다.




2.  regsvr32.exe 활용


regsvr32.exe 는 


C:\Windows\System32 경로에 존재합니다.



참고 64비트 버전의 Windows 운영 체제에는 다음과 같은 두 가지 버전의 Regsv32.exe 파일이 있습니다.

  • 64비트 버전은 %systemroot%\System32\regsvr32.exe입니다.
  • 32비트 버전은 %systemroot%\SysWoW64\regsvr32.exe입니다.



regsvr32.exe 사용중 오류는 msdn 문제 해결 방법이 제일 무난한것 같습니다.



https://support.microsoft.com/ko-kr/kb/249873






사용방법은


관리자 권한으로 cmd 를 연 후


등록 : regsvr32 xxxx.dll

등록해제 : regsvr32 xxxx.dll /u


인데


regsvr32 를 찾지 못할경우 system 경로로 이동하여 실행하거나


regsvr32 만 필요한 경로에 복사하여 사용하여도 됩니다.



regsvr32 는 C, CPP, ATL dll 을 올리기 위한 용도이고


같은 방법으로 regasm 을 활용하면 C# dll 을 올릴수 있습니다.


3. Install Uitility


인스톨 쉴드, 인스톨 팩토리등 인스톨 관련 유틸리티를 활용하여


setup.exe 파일을 만들경우 dll 을 등록하는 메뉴도 있기에 설치하며 등록 할 수도 있습니다.









'Programming > C,CPP,CS' 카테고리의 다른 글

Log4cxx Tutorial  (0) 2016.06.28
Log Librarys  (0) 2016.06.27
Free Dia Diagram Editor  (0) 2016.04.28
Windows 버전별 기본 포함 .NET Framework  (0) 2016.04.14
c# dll ClassLibrary 에서 MessageBox.Show(text,title);  (0) 2016.04.06

c, cpp, com, atl, stl, vc7 String

Programming/C,CPP,CS 2016. 3. 28. 10:14 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


. C 자료형

    char (1) , short (2) , int (4) , long (4), float (4) , double (8) , bool 

    문자 : char

    char szName[20] = "kim";


 

2. WIN API 자료형

 

    BYTE (1,unsigned char) , WORD (2,unsigned short) , UNIT (4, unsigned int) , 

    DWORD (4,unsigned long) , LONG (4,long) , BOOL

    문자 : UCHAR (unsigned char)

    핸들 : 대상을 구분하는 4바이트 정수(HWND, HDC 등)

 

    MBCS문자(열)                 유니코드문자(열)           자동매크로문자(열)

    char                                     wchar_t                              TCHAR

    LPSTR(char*)                    LPWSTR(wchar_t*)        LPTSTR

    LPCSTR(const char*)      LPCWSTR                         LPCTSTR

 

    (참조1) 문자열에 대해 그냥 습관적으로 LPTSTR 또는 LPCTSTR 를 써라

    (참조2) 헝가리안명명법 

                   w(WORD) , dw(DWORD) , i(int) , b(BOOL) , ch(문자) , sz(문자열) , h(핸들)

                   cb(바이트수) , a(배열)

 (참조3) OLECHAR(wchar_t), LPOLESTR(LPWSTR), LPCOLESTR(LPCWSTR), OLESTR(x) = _T(x)


 

3. COM 스트링


    BSTR : 문자열길이를 시작전에 저장하고, 이어서 유니코드문자열을 저장하는 방식
                  1> LPCWSTR ->  BSTR : 생성안됨. 생성함수를 이용해야함
                               BSTR bstr = sysAllocString(L"Hi Bob"); // 메모리할당

                              sysFreeString(bstr); // 메모리제거

                  2> BSTR  ->  LPCWSTR : 형변환 가능

 

    VARIANT : 문자열이 들어올때  BSTR과 동일

 

4. CRT(c runtime library) 지원 스트링클래스

 

    _bstr_t : BSTR랩퍼클래스, 메모리할당/제거를 자동으로 수행

                  1> LPCSTR, LPCWSTR  -> _bstr_t 
                               _bstr_t bs1 = "char string";  // 생성

                  2> _bstr_t  ->  LPCSTR, LPCWSTR 
                               LPCSTR psz1 = (LPCSTR)bs1; // 형변환

                  3> _bstr_t  ->  BSTR : 형변환안됨함수이용
                               BSTR bstr = bs1.copy();

                               sysFreeString(bstr);  // BSTR은 사용후 메모리해제를 해야하는 불편이있음..

 

    _variant_t : VARIANT랩퍼클래스, 메모리할당/제거를 자동으로 수행

                  1> LPCSTR, LPCWSTR  -> _variant_t 
                               _variant_t v1 = "char string"; // 생성

                  2> _variant_t  -> _bstr_t  ->  LPCSTR, LPCWSTR 
                               LPCSTR psz1 = (LPCSTR)(_bstr_t)v1;  //형변환

 

5. ATL 지원 스트링클래스

 

    CComBSTR : BSTR랩퍼클래스, 메모리할당/제거를 자동으로 수행

                  1> LPCSTR, LPCWSTR  ->  CComBSTR 

                               CComBSTR bs1 = "char string"; // 생성

                  2> CComBSTR  ->  BSTR   -> LPCWSTR

                               BSTR bstr = (BSTR)bs1;  // 형변환

 

                  (참조) BSTR -> CComBSTR 

                               CComBSTR bs2; bs2.Attach(W2BSTR(L"Bob"))

                              

    CComVariant : VARIANT랩퍼클래스, 메모리할당/제거를 자동으로 수행

                  1> LPCSTR, LPCWSTR  ->  CComVariant 

                               CComVariant bs1 = "char string"; // 생성

                  2> CComVariant  ->  CComBSTR   ->  BSTR   -> LPCWSTR

                               CComBSTR bs2 = bs1.bstrVal;

 

6. STL 스트링

 

    string 

                  1> LPCSTR -> string

                                string  str = "char string"; //생성

                  2> string -> LPCSTR : 형변환 안됨. 함수이용 

                                LPCSTR psz = str.c_str();

    wstring

                   1> LPCWSTR -> wstring

                                wstring  str = "wide char string"; //생성

                  2> wstring -> LPCWSTR : 형변환 안됨. 함수이용 

                                LPCWSTR psz = str.c_str();

 

7. MFC 스트링

 

    CString

                  1> LPCSTR, LPCWSTR  ->  CString 

                                CString  str = "char string"; //생성

                  2> CString  -> LPCTSTR :

                                LPCTSTR  lpsz = (LPCTSTR)str; //형변환

 

                  (참고)  CString  -> LPTSTR :  함수이용

                               LPTSTR lptsz  = str.GetBuffer(0); str.ReleaseBuffer(); //  올바른 사용

                               LPTSTR lptsz  = (LPTSTR)(LPCTSTR)str  //  잘못된 사용

                               CString  -> BSTR  

                               BSTR bstr = str.AllocSysString(); sysFreeString(bstr)

 

8. VC7 스트링

 

    String : .NET에서 새로 정의한 스트링 클래스

                               String* s1 = S"this is nice"; // 생성

                               CString s2(s1); // 형변환


출처 : http://hacheo.egloos.com/3891296


CPP 기본 예외처리

Programming/C,CPP,CS 2016. 3. 28. 09:21 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

try

{

// Exception 발생 구문

}

catch (std::exception&  e)

{

e.what(); // 활용하여 예외처리


}




https://msdn.microsoft.com/ko-kr/library/c4ts6d5a.aspx


336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

지역 : 천안, 아산, 청주


종목 : 프로그래밍, 정보올림피아드, CCNA, CCNP


경력 : 지도학생) 2013 초등부 정보올림피아드 전국대회 은상 수상

         전) 서울 서울특별시립종합직업전문학교 외부강사

         전) 천안 그린컴퓨터학원 프로그래밍 강사


         현) 청주 그린컴퓨터학원 프로그래밍 강사

         현) 아산소재 대학교 시간강사

         현) 천안소재 대학교 시간강사

         현) 대학원 박사과정 재학중




자세한 문의는


tansanc23@gmail.com 으로 문의해 주세요.

공일공-구구육이-일사일칠



CPP 학생 관리 프로그램

실습과제 모음 2014. 4. 26. 16:18 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

#include <iostream>

#include <string>

using namespace std;

// 학생관리프로그램

// 로그인

// 관리자or 학생

// 1~4학년의학생이존재한다.

// 1학년: 성적확인, 이름, 성적

// 2학년: 성적확인, 이름, 성적

// 3학년: 성적확인, 전공변경, 이름, 성적, 전공

// 4학년: 성적확인, 전공변경, 졸업요건확인, 이름, 성적, 전공

// 관리자모드

// 학생등록

// 학생수정

// 학생삭제

// 성적입력

class FreshMan

{

public:

    string name;

    double grade;

};

class StudentInfo

{

public:

    string studentNumber;

    string name;

    int grade;

};

 

 

int main( )

{

    StudentInfo si[100];

    int siCount = 0;

 

    while(1)

    {

        string loginName;

        cout << "로그인: " << endl;

        cout << "(학생일경우학번, 관리자일경우admin 을입력하세요" << endl;

        cin >> loginName;

 

        while(1)

        {

            if( loginName == "admin" )

            {

                system("cls");

               cout << "Admin 모드로시작합니다." << endl;

                // Admin Mode Start

                cout << "======Menu======" << endl;

                cout << "=1. 학생등록 =" << endl;

                cout << "=2. 학생수정 =" << endl;

                cout << "=3. 학생삭제 =" << endl;

                cout << "=4. 성적입력 =" << endl;

                cout << "=5. 나가기  =" << endl;

                cout << "================" << endl;

                int mode;

                cin >> mode;

                if( mode == 1 )

                {

                    system("cls");

                    cout << "= 학생등록Mode =" << endl;

                    cout << "학번:" ;

                    cin >> si[siCount].studentNumber;

                    cout << "이름:" ;

                    cin >> si[siCount].name;

                    cout << "학년:" ;

                    cin >> si[siCount].grade;

                    siCount++;

 

                    cout << "등록완료" << endl;

                }

                else if( mode == 5 )

                {

                    break;

                }

            }

            else

            {

                cout << "학생모드로시작합니다." << endl;

                cout << "학번: " << loginName << endl;

 

            }

        }

    }

    return 0;

}

'실습과제 모음' 카테고리의 다른 글

반복문 실습 별찍기 예제  (0) 2014.05.31
CPP 문자열 찾기 실습 답  (0) 2014.04.26
CPP 문자열 클래스 실습  (0) 2014.04.26
studentInfo 실습  (1) 2014.04.19
C 배열 연습문제  (0) 2014.04.13