소스 파일명: testArgumentsCli.cpp
  1. // Filename: testArgumentsCli.cpp
  2. //
  3. // Compile: cl /clr testArgumentsCli.cpp
  4. // Execute: testArgumentsCli
  5. using namespace System;
  6. int main(array<System::String ^> ^args)
  7. {
  8.     int i;
  9.     double sum = 0.0;    // 초기화
  10.     // 명령행 인자(command-line argument) 개수 출력
  11.     Console::WriteLine("Count of arguments: {0}", args->Length);
  12.     for (i = 0; i < args->Length; i++) {
  13.         // 스트링을 배정밀도 부동소수점수로 변환하여 누적
  14.         sum += Convert::ToDouble(args[i]);
  15.     }
  16.     // 배정밀도 부동소수점수 값을 출력 
  17.     Console::WriteLine("The sum of arguments is {0}", sum);
  18.     return 0;
  19. }


컴파일> cl /clr testArgumentsCli.cpp

실행> testArgumentsCli 1 2 3 4
Count of arguments: 5
The sum of arguments is 10

실행> testArgumentsCPP 1 2 3 4.1
Count of arguments: 5
The sum of arguments is 10.1





Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.


Posted by Scripter
,

C++/CLI는 Visual C++ 2008 부터 등장한 .NET 용 새로운 C++ 프로그램 언어이다.
이는 Visual C++ 2005에 쓰이던 MC++(Mananged C++)의 약점을 보완하며 대체한다.

[참고 자료]
    1. http://www.codeproject.com/KB/mcpp/cppcliintro01.aspx
    2. http://blog.voidnish.com/index.php?p=11
    3. http://recoverlee.tistory.com/37?srchid=BR1http%3A%2F%2Frecoverlee.tistory.com%2F37


 
------------------------------[소스 시작]
// Filename: helloWorldCli.cpp
//
// Compile: cl /clr helloWorldCli.cpp
// Execute: helloWorldCli

using namespace System;
 
int main(array<System::String ^> ^args)
{
    Console::WriteLine("Hello, world!");
    Console::WriteLine("안녕하세요?");
    return 0;
}
------------------------------[소스 끝]


컴파일> cl /clr helloWorldCli.cpp
실행> helloWorldCli
Hello, world!
안녕하세요?


크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


[파일명:  testStringFindInList.cpp]------------------------------------------------
#include <iostream>
#include <functional>
#include <algorithm>
#include <string>
#include <list>

using namespace std;

struct SData {
    SData(string s) : m_s(s) {}
    string m_s;
};

namespace std {
    template <> struct greater<SData*> {
        bool operator()(SData const* p1, SData const* p2) {
            //Defined like less for ascending sorting
            if(!p1)
                return true;
            if(!p2)
                return false;
            return p1->m_s < p2->m_s;
        }
    };
};

// Predicate class
class MyPred {
private:
    std::string     m_strForFind;

public:
    // for find_if
    void setQuery(std::string str) {
        m_strForFind = str;
    };

    // operator override for find_if
    bool operator()(SData const* p) {
        if(!p)
            return false;
        int n = (p->m_s).find(m_strForFind);
        int m = (p->m_s).length();
        return n >= 0 && n < m;
    };
};

void printList(list<SData*> lst);

int main() {
    list<SData*> mylist;
    mylist.push_back(new SData("하나"));
    mylist.push_back(new SData("둘"));
    mylist.push_back(new SData("셋"));
    mylist.push_back(new SData("넷"));
    mylist.push_back(new SData("다섯"));
    mylist.push_back(new SData("여섯"));

    cout << "list: ";
    printList(mylist);

    MyPred pred;
    pred.setQuery("셋");
    list<SData*>::iterator it;
    it = find_if(mylist.begin(), mylist.end(), pred);
    if (it != mylist.end()) {
        cout << "발견!  ";
        cout << "Next word of 셋 in list: " << (*(++it))->m_s << endl;
    }

    // Sorting list in ascending order
    cout << "Sorting..." << endl;
    mylist.sort(greater<SData*>());

    cout << "list: ";
    printList(mylist);

    it = find_if(mylist.begin(), mylist.end(), pred);
    if (it != mylist.end()) {
        cout << "발견!  ";
        cout << "Next word of 셋 in list: " << (*(++it))->m_s << endl;
    }

    for (it = mylist.begin(); it != mylist.end(); it++)
        delete *it;

    return 0;
}

void printList(list<SData*> lst) {
    list<SData*>::iterator it;
    list<SData*>::iterator it2;
    cout << "[";
    for (it = lst.begin(); it != lst.end(); it++) {
     it2 = it;
        advance(it2, 1);
        if (it2 == lst.end())
            break;
        cout << (*it)->m_s << ", ";
    }
    if (lst.size() > 0)
        cout << (*it)->m_s;
    cout << "]" << endl;
}
------------------------------------------------


Visual C++의 경우:
컴파일> cl /EHsc testStringFindInList.cpp
또는
Borland C++의 경우:
컴파일> bcc32 testStringFindInList.cpp
또는
Cywin이나 Msys의  g++의 경우:
컴파일> g++ -o testStringFindInList testStringFindInList.cpp

실행> testStringFindInList
list: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in list: 넷
Sorting...
list: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in list: 여섯


Cywin이나 Msys의  g++의 경우:
실행> ./testStringFindInList
list: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in list: 넷
Sorting...
list: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in list: 여섯



크리에이티브 커먼즈 라이선스
Creative Commons License

 


Posted by Scripter
,


[파일명:  testStringFindInVector.cpp]------------------------------------------------
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

void printArray(vector<string>  arr);

int main() {
    int SIZE = 6;
    string data[] = { "하나", "둘", "셋", "넷", "다섯", "여섯" };
    vector<string> words(&data[0], &data[SIZE]);
    vector<string>::iterator it;

    /////////////////////////////////
    // words[0] = "하나";
    // words[1] = "둘";
    // words[2] = "셋";
    // words[3] = "넷";
    // words[4] = "다섯";
    // words[5] = "여섯";

    cout << "vector: ";
    printArray(words);

    it = find(words.begin(), words.end(), "셋");
    if (it != words.end()) {
        cout << "발견!  ";
        cout << "Next word of 셋 in vector: " << *(++it) << endl;
    }

    cout << "Sorting..." << endl;
    sort(words.begin(), words.end());

    cout << "vector: ";
    printArray(words);

    it = find(words.begin(), words.end(), "셋");
    if (it != words.end()) {
        cout << "발견!  ";
        cout << "Next word of 셋 in vector: " << *(++it) << endl;
    }
     return 0;
}

void printArray(vector<string> v) {
    cout << "[";
    for (int i = 0; i < v.size() - 1; i++) {
        cout << v[i] << ", ";
    }
    if (v.size() > 0)
        cout << v[v.size() - 1];
    cout << "]" << endl;
}
------------------------------------------------


Visual C++의 경우:
컴파일> cl /EHsc testStringFindInVector.cpp
또는
Borland C++의 경우:
컴파일> bcc32 testStringFindInVector.cpp
또는
Cywin이나 Msys의  g++의 경우:
컴파일> g++ -o testStringFindInVector testStringFindInVector.cpp

실행> testStringFindInVector
vector: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in vector: 넷
Sorting...
vector: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in vector: 여섯


Cywin이나 Msys의  g++의 경우:
실행> ./testStringFindInVector
vector: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in vector: 넷
Sorting...
vector: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in vector: 여섯



크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


[파일명:  testStringFindApp.cpp]------------------------------------------------
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

void printArray(string arr[], int size);

int main() {
   // string words[] = { "one", "two", "three","four", "five"};
   int SIZE = 6;
   string words[] = { "하나", "둘", "셋", "넷", "다섯", "여섯" };
   string* where;

   cout << "array: ";
   printArray(words, SIZE); 
   where = find(words, words + SIZE, "셋");
   if (where - words < SIZE)
       cout << "발견!  ";
   if (where != &words[SIZE])
       cout << "Next word of 셋 in array: " << (*++where) << endl;

   cout << "Sorting..." << endl;
   sort(words, words + SIZE);

   cout << "array: ";
   printArray(words, SIZE); 
   where = find(words, words + SIZE, "셋");
   if (where - words < SIZE)
       cout << "발견!  ";
   if (where != &words[SIZE])
       cout << "Next word of 셋 in array: " << (*++where) << endl;

    return 0;
}

void printArray(string arr[], int size) {
    cout << "[";
    for (int i = 0; i < size - 1; i++) {
       cout << arr[i] << ", ";
    }
    if (size> 0)
        cout << arr[size - 1];
    cout << "]" << endl;
}
------------------------------------------------


Visual C++의 경우:
컴파일> cl /EHsc testStringFindApp.cpp
또는
Borland C++의 경우:
컴파일> bcc32 testStringFindApp.cpp
또는
Cywin이나 Msys의  g++의 경우:
컴파일> g++ -o testStringFindApp testStringFindApp.cpp

실행> testStringFindApp
array: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in array: 넷
Sorting...
array: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in array: 여섯


Cywin이나 Msys의  g++의 경우:
실행> ./testStringFindApp
array: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in array: 넷
Sorting...
array: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in array: 여섯



크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


[파일명:  testSortApp.cpp]------------------------------------------------
using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;

void printArray(array<String^>^ arr);

int main(int argc, char *argv[]) {
    array<String^>^ arr = gcnew array<String^>(argc - 1);
    for (int i = 1; i < argc; i++) {
        arr[i-1] = gcnew String(argv[i]);
    }
    Array::Sort(arr);
    printArray(arr);
}
  
void printArray(array<String^>^ arr) {
    Console::Write("[");
    for (int i = 0; i < arr->Length - 1; i++) {
        Console::Write("{0}, ", arr[i]);
    }
    if (arr->Length > 0)
        Console::Write("{0}", arr[arr->Length - 1]);
    Console::WriteLine("]");
}
------------------------------------------------


Visual C++의 경우:
컴파일> cl /clr testSortApp.cpp

실행> testSort one two thee four five
[five, four, one, three, four]

실행> testSortApp 하나 둘 셋 넷 다섯
[넷, 다섯, 둘, 셋, 하나]


 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


[파일명:  testSort.cpp]------------------------------------------------
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

void printArray(string arr[], int size);

int main(int argc, char *argv[]) {
   string words[100];
   int nSize;
   if (0 < argc & argc < 100) {
       for (int i = 1; i < argc; i++) {
           words[i - 1] = argv[i];
       }
       nSize = argc - 1;
       sort(words, words + nSize);
       printArray(words, nSize);
   }
    return 0;
}

void printArray(string arr[], int size) {
   cout << "[";
   for (int i = 0; i < size - 1; i++) {
       cout << arr[i] << ", ";
   }
   if (size > 0)
       cout << arr[size - 1];
   cout << "]" << endl;
}
------------------------------------------------

Visual C++의 경우:
컴파일> cl /EHsc testSort.cpp
또는
Borland C++의 경우:
컴파일> bcc32 testSort.cpp
또는
Cywin이나 Msys의  g++의 경우:
컴파일> g++ -o testSort testSort.cpp

실행> testSort 하나 둘 셋 넷 다섯
[넷, 다섯, 둘, 셋, 하나]

실행> testSort one two thee four five
[five, four, one, three, four]

Cywin이나 Msys의  g++의 경우:
실행> ./testSort 하나 둘 셋 넷 다섯
[넷, 다섯, 둘, 셋, 하나]

실행> ./testSort one two thee four five
[five, four, one, three, four]



 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 C++ 소스이다.

/*
 * Filename: makeMultTableCPP.cpp
 *
 *     Print a multiplication table.
 *
 *     Compile: cl /EHsc makeMultTableCPP.cpp
 *     Execute: makeMultTableCPP 230 5100
 *
 * Date: 2009/03/07
 * Author: pkim (AT) scripts.pe.kr
 */

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

void printUsing();
void printMultTable(int x, int y);

int main(int argc, char *argv[]) {
    long x, y;
    if (argc >= 3) {
        x = atoi(argv[1]);
        y = atoi(argv[2]);
        cout << endl;
        printMultTable(x, y);
    }
    else {
        printUsing();
    }
}

void printUsing() {
    cout << "Using: makeMultTable [number1] [number2]" << endl;
    cout << "Print a multiplication table for the given two integers." << endl;
}

void printMultTable(int x, int y) {
    char strX[80];
    char strY[80];
    char strZ[80];
    char strT[80];
    char zeros[80];
    char whites[80];
    char bars[80];
    char line1[80];
    char line2[80];
    char line3[80];
    char line4[80];
    char loffset[20];
    char buf[80];

    long nx = (x >= 0) ? x : - x;
    long ny = (y >= 0) ? y : - y;
    int ntail1 = 0;
    int ntail2 = 0;
    while (nx % 10L == 0L) {
        nx = nx / 10L;
        ntail1++;
    }
    while (ny % 10L == 0L) {
        ny = ny / 10L;
        ntail2++;
    }
    long z = nx * ny;
    sprintf(strZ, "%ld", z);
    sprintf(strX, "%ld", nx);
    sprintf(strY, "%ld", ny);
    int n = strlen(strY);
    strcpy(zeros, "0000000000000000000000000000000000000000");
    strcpy(whites, "                                        ");
    strcpy(bars, "----------------------------------------");
    strcpy(loffset, "       ");
    sprintf(line4, "%s%ld", loffset, nx*ny);
    strncpy(buf, zeros, ntail1 + ntail2);
    buf[ntail1 + ntail2] = '\0';
    strcat(line4, buf);
    strcpy(line1, loffset);
    strncpy(buf, whites, strlen(strZ) - strlen(strX));
    buf[strlen(strZ) - strlen(strX)] = '\0';
    strcat(buf, strX);
    strcat(line1, buf);
    strncpy(buf, zeros, ntail1);
    buf[ntail1] = '\0';
    strcat(line1, buf);

    strcpy(line2, "   x ) ");
    strncpy(buf, whites, strlen(strZ) - strlen(strY));
    buf[strlen(strZ) - strlen(strY)] = '\0';
    strcat(buf, strY);
    strcat(line2, buf);
    strncpy(buf, zeros, ntail2);
    buf[ntail2] = '\0';
    strcat(line2, buf);

    strcpy(line3, "     --");
    strncpy(buf, bars, strlen(strZ));
    buf[strlen(strZ)] = '\0';
    strcat(line3, buf);

    cout << line1 << endl;
    cout << line2 << endl;
    cout << line3 << endl;
    if (strlen(strY) > 1) {
        for (int i = 0; i < strlen(strY); i++) {
         buf[0] = strY[strlen(strY) - i - 1];
         buf[1] = '\0';
            int y1 = atoi(buf);
            if (y1 != 0) {
                sprintf(strT, "%ld", nx * y1);
                strcpy(line2, loffset);
                strncpy(buf, whites, strlen(strZ) - strlen(strT) - i);
                buf[strlen(strZ) - strlen(strT) - i] = '\0';
                strcat(buf, strT);
                strcat(line2, buf);
                cout << line2 << endl;
            }
        }
        cout << line3 << endl;
    }
    cout << line4 << endl;
}





컴파일> cl /EHsc makeMultTableCPP.cpp
실행> makeMultTableCPP 230 5100
결과>

          230
   x )   5100
     ------
         23
       115
     ------
       1173000

 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


아래의 소스는 http://www.fredosaurus.com/notes-cpp/examples/rpn/rpn.html 에
올려져 있는 그대로의 (명령행 RPN 계산기) C++ 소스입니다.
소스가 매우 간단하다.

그러나 부족한 점이 몇 가지 눈에 띤다.

      1) 소수점 있는 수를 처리하지 못한다.
      2) 음수를 피연산자로 쓸 수 없다.
      3) 기타

이런 점을 개선한 소스는  http://www.scripts.pe.kr/wiki/wiki.php/RPNCalc 에서 볼 수 있다.

// stl/rpn.cpp -- RPN (Reverse Polish Notation) Calculator
// Fred Swartz 2001-12-05, 2002-09-27
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;

int pop(vector<int>& stk);  //--- prototype to pop stack

//============================================================= main
int main() {
    vector<int> opndStack; // vector used as operand stack
    string token;          // to read number or operator

    while (cin >> token) {
        if (isdigit(token[0])) { // if first is digit, it's number.
            opndStack.push_back(atoi(token.c_str())); // convert, push
           
        } else { // If it's not a number, assume it's an operator
            int left, right;  //  used by some operators as temps

            switch (token[0]) {  // assume operators are one char
              case '+': opndStack.push_back(pop(opndStack) + pop(opndStack));
                        break;
              case '-': right = pop(opndStack); // get right operand
                        left  = pop(opndStack); // get left operand
                        opndStack.push_back(left - right);
                        break;
              case '*': opndStack.push_back(pop(opndStack) * pop(opndStack));
                        break;
              case '/': right = pop(opndStack); // get right operand
                        left  = pop(opndStack); // get left operand
                        opndStack.push_back(left / right);
                        break;
              default:  throw domain_error("Undefined operator");
            }
            cout << "Result: " << opndStack.back() << endl;
        }
    }
    return 0;
}//end main

//============================================================== pop
   // This utility function checks stack for underflow
   // and pops (removes and returns) last element.
int pop(vector<int>& stk) {
    if (stk.empty()) {
        throw underflow_error("Stack underflow.");
    }
    int result = stk.back();
    stk.pop_back();
    return result;
}//end pop


 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,
Posted by Scripter
,