2012년 10월 19일 금요일

[C++] assert() 의 사용


1. 알아 둘 내용
assert() 는 견고한 프로그래밍을 위해 디버깅용으로 많이 사용 한다고 한다.
실행 결과에서 처럼 소스의 어느 부분에서 에러가 발생 하였는지 조금 더 자세히 알 수 있다.
NDEBUG 가 설정 되어 있으면 assert() 부분을 건너 뛴다고 한다. NDEBUG 알아 볼 것.


2. 소스 내용
#include <iostream>
#include <cassert>  /* C++ 에서 assert() 를 사용 */

using namespace std;

int main() {

 cout << "program start" << endl;

 int x = 1;

 assert(x == 2);

 cout << "program end" << endl;

 return 0;
}


3. 실행 결과

program start

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Assertion failed!

Program: D:\study\workspace\cpp_exam_2\Debug\cpp_exam_2.exe
File: ..\src\cpp_exam_2.cpp, Line 19

Expression: x == 2

[C++] 난수 만들기

1. 소스 내용
#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

int randNum(){

 srand(time(NULL));

 for(int x = 0 ; x <= 10 ; x++){
  cout << rand() % 10 +1 << endl;
 }
}

int main() {

 randNum();

 return 0;
}

2. 실행 결과
   : 실행 할 때 마다 결과가 달라진다.
6
9
10
10
1
7
5
7
9
8
5

[C++] vector, iterator 예제


1. 소스 내용
#include <iostream>
#include <vector>

using namespace std;

int main() {

 vector<string> vStr;
 vStr.push_back("hello");
 vStr.push_back(" world");
 vStr.push_back("!!\n");

 vector<string>::iterator itor;

 for(itor = vStr.begin();itor != vStr.end();itor++){
  cout << *itor;
 }

 return 0;
}


2. 실행 결과

hello world!!

2012년 10월 15일 월요일

[C++] pid 알아내기


1. 소스내용
#include <iostream>
#include <unistd.h> /*  getpid() 를 사용 하기 위해 필요 */

using namespace std;


int main() {

 cout << (unsigned)getpid() << endl;

 cin.get();

 return 0;
}


2. 실행 결과

/* 일반 사용자의 계정에서 실행 */
[freecatz@localhost pid]$ ./pidCheck
1667

/* root 의 권한으로 특정 프로세스 목록을 출력 */
[root@localhost ~]# ps -ef | grep -i pidCheck | grep -v grep
freecatz  1667  1602  0 01:43 pts/0    00:00:00 ./pidCheck
[root@localhost ~]#

2012년 10월 9일 화요일

[C++] 파일 입출력 예제


1. 소스 내용
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <io.h>
/* 
    윈도즈의 경우 access() 사용을 위해 io.h 가 필요 하나, linux 의 경우 io.h 가 없어도 컴파일이 된다.
*/

void readFile();
void createFile();

using namespace std;

int main() {

 int chk = access("c:\\d.txt", 0);
 // int chk = access("//home//freecatz//d.txt", 0);

 if (chk == 0) {
  cout << "file found" << endl;
  readFile();
 } else {
  cout << "file not found" << endl;
  createFile();
 }

 return 0;
}

void readFile() {
 ifstream file("c:\\d.txt");
// ifstream file("//home//freecatz//d.txt");

 char ch;

 while (!file.eof()) {
  file.get(ch);
  // getline() 에 대해서 알아 볼 것.

   cout << ch;
 }
}

void createFile() {
 ofstream file("c:\\d.txt");
// ofstream file("//home//freecatz//d.txt");

 file << "this is test file ...\nhello world" << endl;

 file.close();
}


2. 실행 결과

파일이 없는 경우 파일을 생성 하고, 파일이 있는 경우 화면에 뿌려 준다.

[C++] 날짜, 시간 가져오기


1. 소스 내용
#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

int main() {

 struct tm* datetime;

 time_t t;

 t = time(NULL);
 datetime = localtime(&t);

 printf("%d/%02d/%02d %02d:%02d:%02d", datetime->tm_year + 1900,
                                                datetime->tm_mon + 1,
                                                datetime->tm_mday,
                                                datetime->tm_hour,
                                                datetime->tm_min,
                                                datetime->tm_sec
    );

 return 0;
}

2. 실행결과

2012/10/09 14:38:28

[C++] 실행 시간 체크


1. 소스 내용
#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

int main() {

 clock_t startTime, endTime;

 startTime = clock();

 int x = 0;

 for (x; x < INT_MAX; x) {
  x += 1;
 }

 cout << "x = " << x << endl;
 endTime = clock();
 cout << "running time " << (float) (endTime - startTime) / CLOCKS_PER_SEC << "sec"
   << endl;

 return 0;
}

2. 실행결과 

x = 2147483647
running time 7.293sec


2012년 10월 3일 수요일

[FuN] 조선시대 최고의 락그룹











그룹 난공불락 이그룹은 기타는 대동여지도 김정호가 했고
보컬은 풍속 김흥도가 했으며 베이스는 4군 6진의 김종서가
마지막으로 드럼은 거북선 이순신이 했다고 락밴드계의
전설로 내려온다
조선시대 최강 그룹 난공불락은
조선팔도 소녀들의 마음을 흔들어놓았고

급기야 이들의 음악을 궐로 보내라는 상소문이 빗발쳤고
이에 세종은 와전된 재래 아악곡을 폐기하고 임우(林宇)의
≪대성악보 大晟樂譜≫에 바탕을 둔 새로운 아악곡을 제정하였다

하지만 대성악보는 외란의 침략을 받아 1592년에 훼손된것으로

현세에 전해지는곡은 이 곡밖에 없다.
하지만 그룹 난공불락은 일본의 소녀들의 마음까지 흔들였으니
세계최초의 한류였다 그후 난공불락은 중국은 물론 몽골과
무굴제국 그리고 중동의 투르크 왕조까지 휩쓸였으니 이에
유럽은 한류를 피해 대항해시대라는 명목으로 아메리카로 피신하였다
그러나 결국 7세기만에 유럽도 정복을 하기 시작하였으며 최후의 보루였던
아메리카의 중추인 미국도 흔들리기 시작하였다는 얘기가 전해진다
예를 들어 영국의 여왕과 딱정벌레 미국의 초록날이라는 이 유명한 그룹도 졌다는 뒷이야기가 전해진다고 한다

그러나 본토에서는 세로운 바람이 일어났으니 바로 막상막하와 천하쟁패라는 신 락밴드 그룹이 등장했으니

이로써 조선에는 락밴드계의 3대 그룹이 서로 견주고 있었으나 결국 마이동풍이라는 사건을 통해 모두 전설로

묻혀졌다는 이야기가 내려오고 있다 -끝-


출처 [클릭