2012. 8. 1. 16:21
import sqlite3
conn = sqlite3.connect('example.db')

c = conn.cursor()

# Create table
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')

# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

# Save (commit) the changes
conn.commit()

# We can also close the cursor if we are done with it
c.close()

 

select 옵션( ?  or %s )

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = (symbol,)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)

# cur.execute("insert into people values (?, ?)", (who, age))
print c.fetchone()

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
                   ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
                   ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
                 ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

 

c.execute   or fetchall()  <-- return  matching rows.

for row in c.execute('SELECT * FROM stocks ORDER BY price'):
        print row

(u'2006-01-05', u'BUY', u'RHAT', 100, 35.14)
(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
(u'2006-04-05', u'BUY', u'MSFT', 1000, 72.0)

 

Connection.create_function(name, num_params, func)

Creates a user-defined function that you can later use from within SQL statements under the function name name. num_params is the number of parameters the function accepts, and func is a Python callable that is called as the SQL function.

The function can return any of the types supported by SQLite: unicode, str, int, long, float, buffer and None.

import sqlite3
import md5

def md5sum(t):
    return md5.md5(t).hexdigest()

con = sqlite3.connect(":memory:")
con.create_function("md5", 1, md5sum)
cur = con.cursor()
cur.execute("select md5(?)", ("foo",))
print cur.fetchone()[0]

 

출처 : http://docs.python.org/library/sqlite3.html

디비구축.zip

Posted by Triany
2012. 5. 10. 17:57

새로운 엑셀파일 생성

import xlwt

wbk = xlwt.Workbook()
sheet = wbk.add_sheet('2012.05', cell_overwrite_ok=True)   #덮어쓰기 가능 설정
sheet.write(0,0,'date')
sheet.write(0,1,"count")
sheet.write(0,2,"size")       #시트에 데이터 기록

wbk.save('test.xls')          #데이터 저장(저장과 동시에 엑셀파일 생성)

xlwt.Workbook() : excel workbook 만들기.

  • wbk.add_sheet("")  : sheet 추가.
  •                                         - cell_overwrite_ok=True 설정을 해 두면 덮어쓰기 가능
  • sheet.write(행, 열, data)로 값 기록
  • wbk.save("file name")으로 file 저장!
  •  

    기존 엑셀 파일로 작업

    (xlrd 모듈 필요)

    다운경로 : http://pypi.python.org/pypi/xlrd/0.7.1

    import xlrd

    xls = xlrd.open_workbook('test.xls',formatting_info=True)  #엑셀파일 open
    sheet_01 = xls.sheet_by_index(0)  # 0번째 시트 정보 가져옴 
    print r_sheet

    엑셀 전체 시트수 : xls.nsheets

    시트 불러오기

    xls.sheet_by_index(0) #index로 불러오기

    xls.sheet_by_name(u'Sheet1') #이름으로 불러오기

    A시트에 대해서

    sheet_01.name : 시트명

    sheet_01.nrows : 시트 행 수

    sheet_01.ncols : 시트 열 수

    firstColumn = sheet_01.col_values(0) #0번째 컬럼 전체 읽어옴

    sheet_01.cell_value(rowx=0, colx = 2) : 1행 C열의 값 반환

    first_column = sh.col_values(0)

     

    엑셀에 한글 입력하기

    book = xlwt.Workbook(encoding='utf-8')
    sheet = book.add_sheet('첫번째시트')
    sheet.write(0, 0, '한글')
    book.save('unicode0.xls')

     

    고급 엑셀 기능 사용 관련 예제 사이트

    https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/examples/

     

    Posted by Triany
    2011. 10. 6. 13:45


    #include <stdio.h>
    void main(){
        int a = 10000;
       printf("[d]  %d\n", a);
       printf("[x]  %08x\n", a);

        for (int i = 0; i < 32; i++)
        {
            a & (0x01 << (31 - i)) ? printf("1") : printf("0");
            if( (i+1) % 4 == 0 )
                  printf(" ");

        }

        printf("(2)\n");
    }


     #include <stdio.h>
    void main(){
       int a;
       a = 0x7d9;
       printf("[d]  %d\n", a);

       //16진수로 출력
       printf("[x]  %08x\n", a);
     
       //8진수 출력
       printf("[o]  %08o\n", a);

        //2진수 표현
        for (int i = 0; i < 32; i++)
        {
          a & (0x01 << (31 - i)) ? printf("1") : printf("0");
          if( (i+1) % 4 == 0 )
            printf(" ");
         }
         printf("(2)\n");

     
          printf("   --- type 별 바이트수 ---\n");
         printf("\tchar  : %d bytes\n", sizeof(char));
         printf("\tshort : %d bytes\n", sizeof(short));
         printf("\tint   : %d bytes\n", sizeof(int));
        printf("\tlong  : %d bytes\n", sizeof(long));
     }




    %o : 8진수
    %x : 16진수
    %d : 10진수

    Posted by Triany
    2011. 4. 3. 23:43

    <cin> : 문자와 문자열 모두 입력 받을 수 있다.
    - 엔터가 나오면 입력종료로 간주.(공백도 마찬가지)

    #include <iostream>
    void main()
    {
     char a, b;
     char str[10];

     cin>>a;  //1
     cout<<a<<endl;  //2


     cin>>a;   //3
     cin>>b;   //4
     cout<<a<<" "<<b<<endl; //5


     cin>>str; //6
     cout<<str<<endl;; //7
     
    }

    1번에서 p를 입력하고 엔터
    2번 출력 결과 => p

    3,4번에서,
    x입력후 엔터, y입력후 엔터
    5번 출력 결과 => x y


    6번에서 loving you 엔터
    7번에서 출력 결과 =>loving



    <get> : get()은 문자만 입력받을 수 있다.

    - 이 함수는 개행문자를 입력 큐에 그대로 남겨둔다.

     #include <iostream.h>
    void main()
    {
     char a, b, c;
     a = cin.get(); //cin.get(a) 가능
     b = cin.get();
     c = cin.get(); //1
     cout<<a<<" "<<b<<" "<< c<<endl; //2
    }

    1번까지
    x입력후 엔터, y입력후 엔터
    [2번 출력 결과]
    x
    y
    -즉 엔터도 입력받을 문자로 간주한것으로 볼 수 있습니다.(공백또한 문자로 간주)
    x + Enter(개행) + y

    cf)cin은 엔터가 나오면 입력 종료로 간주.


    cf)getline와 get함수가 다른 점은 get함수는 개행문자를 읽어서 버리지 않고 입력큐에 그대로 남겨둔다는 점이다.

    즉, cin.get(str1, hi);
        cin.get(str2, hello);
    라는 두 문장이 있다면 입력큐에 개행문자가 그대로 있어서 두번째 호출은 개행문자를 첫 문자로 만나게 된다.
    굳이 get()을 써야 한다면,
     cin.get(str1, hi);
     cin.get();
     cin.get(str2, hello);
    이렇게 두 문장사이에 get()을 하나 더 삽입하면 된다.

    파일에서 읽어들여 올때.. 간단한 사용법

     read ( ifstream  *input_file )
    {
     char c;
     while (1)
     {
      input_file->get(c);
      if ( input_file->eof() )
       break;
      else
       cout<<c;
     }
    }
     //or
    read ( ifstream *input_file )
    {
     char c;

     input_file->get(c);
     while (!input_file->eof())
     {
      cout<<c;
      input_file->get(c);
     }
    }

     //or ... 이게 제일 편한 방법인듯.
    read ( ifstream *input_file )
    {
     char c;

     while ( input_file->get(c) )
      cout<<c;
    }


     

    <getline> : getline()은 문자열만 입력 받는다.
    getline(변수의 주소, 최대입력가능 문자수, 종결문자);
    -getline()gkatnsms Enter키가 전달하는 개행문자를 입력의 끝으로 인식하여 한줄 전체를 읽는다.
    -종결문자 생략시 엔터로 간주된다. 그리고 종결문자를 NULL문자로 바꾼다. 따라서 종결문자전까지 출력하게 된다.
    최대입력가능 문자수보다 많은 문자를 입력한 경우 n-1개만큼만 받아들이고 n번째 문자는 null문자로 취급한다.
    -cin.getline(a,20); //이때 입력한 문자의 개수는 19개이하이여야 한다.(마지막 1문자는 null문자 삽입)

     #include<iostream>
    void main()

    {
     char a[10];
     cin.getline(a,10); //1
     cout<<a<<endl;  //2

     cin.getline(a, 10, 'u'); //3
     cout<<a<<endl;  //4

    }

    1번에서 so cute! 입력후 엔터
    2번 결과 => so cute!
    cf)cin의 경우 공백이 나오면 입력이 끝났다고 간주, but getline은 공백(ascii 32)도 문자로 받아들임

    3번에서 so cute! 입력후 엔터
    4번 결과 => so c


     

    파일에서 읽어올 경우.. infile->getline(이 위치로, 문자수, 종결문자) 형식.
    read(ifstream  *infile) 
    {

     SMS S;
     while(!infile->eof())
     { 
      infile->getline(S.phone,21,'\n');
      infile->getline(S.msg, 97,'\n');
      S.time = currentTime();
      insert(S);
     }
    }

    Posted by Triany
    2011. 3. 25. 17:54
    출처 : http://www.devarticles.com/c/a/cplusplu ··· right%2F
    출처:http://webdizen.new21.net/blog/3110

    Are you looking for a way to speed up the debugging process in C++? This article explains how to use asserts to do just that, showing that not all macros are evil.

    If a man begins with certainties, he shall end in doubts;

    But if he will be content to begin with doubts,

    He shall end in certainties.

    [Francis Bacon 1561-1626]

    Assertive Programming

    If there is one thing I have learned over the past few years, it is not to underestimate the power of assert(). It comes with your compiler and can be found either in cassert or assert.h.

    The reason I love assert is because it looks after me and helps me find bugs I was sure weren’t there. I mean, we all write bugfree software, right? Yeah right. Well there have been many Kodak moments when an assert fired on something I was dead sure could never happen; I should be a rich man as the look on my face was priceless.

    If you are not familiar with asserts, you should start using them right now. Use  assert to check that your code is working the way you expect it to or be prepared to pay the price. No not for my face, but for long nights behind the debugger, ticking away possible problem sources until you have your own Kodak moment.

    When do you use assert, you ask? Simple… whenever you can use it to verify the truth of a situation: ‘this pointer can never be null’, ‘this number is never smaller than zero’, ‘there is always at least one customer stored in this list’, ‘this code won’t be used the next millennium, two digits are fine’.

    Use proper error handling when you can check for things that can go wrong. Use asserts on things you are sure can’t go wrong.

    Trust me… the sillier the assert… the more valuable it is. I tested this once myself, grinning, thinking ‘this is ridiculous, want to bet it will never fire?’, only to have it triggered a couple of months later! And because the assert was so preposterous and silly I immediately knew which conditions were breaking my code.

    assert.

    1. To state or express positively, affirm: asserted his innocence
    2. To defend or maintain (one’s rights, for example)

    The important thing to remember is that asserts are only compiled into your code when the NDEBUG macro is not defined. So in the final optimized version of your application, they are not there to bloat or to slow things down! The only investment you have to make is typing them out while you are working on those classes and functions. It will pay you back greatly when it helps you shorten the time it takes to track down bugs.

    Face it… we all write code on assumptions we make about the situation the code will be running in. Assert you are in that situation, because your code base will grow beyond the picture you have of it in your mind.

    Though we will be implementing our customized version of assert here, all you need to do is include assert.h and you are ready to use the assert macro that comes with it:

    // assert.h
    #ifndef NDEBUG
    void __assert(const char *, const char *, int);
    #define assert(e) \
         ((e) ? (void)0 : __assert(#e,__FILE__,__LINE__))
    #else
    #define assert(unused) ((void)0)
    #endif

    The __assert helper function prints an error message to stderr and the program is halted by calling abort(). It is possible that the implementation that comes with your compiler varies slightly, but you get the idea.

    Lets use a simple example function:

    void writeString(char const *string) {
    assert( 0 != string );
    ...
    }

    In the unfortunate situation that the pointer to string is NULL, execution will halt and you will be offered the possibility of opening the debugger and jumping to the location in the source where the assertion failed. This can be very handy as you can examine the call stack, memory, registers, and so forth, and are likely to catch the perpetrator red handed!

    Although I am ranting about why you should use assert, this article is aimed at showing you how to implement your own version using preprocessor macros.

    Here is a very basic version that doesn’t even halt execution:

    #ifndef NDEBUG
    # define ASSERT( isOK ) \
    ( (isOK) ? \
         (void)0 : \
         (void)printf(“ERROR!! Assert ‘%s’ failed on line %d ” \
          “in file ‘%s’\n”, #isOK, __LINE__, __FILE__) )
    #else
    # define ASSERT( unused ) do {} while( false )
    #endif

    Notice that we don’t need a helper function to get information onto the screen. (I am sticking to printf in the following examples, but there is nothing stopping you from using fprintf and stderr instead.) The stringize macro operator (#) names the condition for us in the printf statement, adding quotes as well and the predefined __LINE__ and __FILE__ macros help to identify the location of the assert.

    The do { } while ( false ) statement for the unused version of assert, I used to make sure that the user cannot forget to conclude his assert statement with a semicolon. The compiler will optimize it away, and I consider it a slightly better way to say that I am not doing anything.

    We are only one step away from halting our application’s execution (don’t forget to include stdlib.h):

    #ifndef NDEBUG
    # define ASSERT( isOK ) \
    if ( !isOK ) { \
     (void)printf(“ERROR!! Assert ‘%s’ failed on line %d “ \
      “in file ‘%s’\n”, #isOK, __LINE__, __FILE__) ); \
     abort(); \
    }
    #else
    # define ASSERT( unused ) do {} while ( false )
    #endif

    In case writeString is called with a NULL pointer now, we are told what went wrong, where it went wrong and the application is halted.

    When you are using the Microsoft Visual C++ 7.1 compiler, you’ll be presented with a dialog screen:


    After pressing Retry you are presented with more dialogs and finally... you end up in the debugger.

    The problem with abort() is that it doesn’t let you resume execution after you’ve concluded that the assert was benign; or maybe you are interested in what happens immediately after the assert? You need to disable the assert (never a good thing), recompile and restart your application.

    There are other ways to halt execution and you will have to look in your compiler’s documentation to discover what the correct call is, but with Visual C++ it’s an interrupt call:

    __asm { int 3 }

    When our application halts again on the writeString function, we’ll encounter the following dialog (did you recognize it? We actually came across this dialog when halting the application with the abort() function!) :

    It is not a problem to continue execution now, if we think this is responsible… that is you are often recommended to implement your own assert functionality.

    Wouldn’t it be nice to be able to add some hints or remarks along with the location of the assert? When the assert fires and you don’t have a debugger available, this message might still tell you what the problem is:

    void writeString(char const *string) {
    assert(0!=string, “A null pointer was passed to writeString()!”);
    ...
    }

    The simplest solution is to just expand the assert macro and make it accept a message as well as a condition:

    #ifndef NDEBUG
    # define ASSERT( isOK, message ) \
    if ( !(isOK) ) { \
     (void)printf(“ERROR!! Assert ‘%s’ failed on line %d “ \
      “in file ‘%s’\n%s\n”, \
         #isOK, __LINE__, __FILE__, #message); \
      __asm { int 3 } \
     }
    #else
    # define ASSERT( unused, message ) do {} while ( false )
    #endif

    Again the stringize operator helps us to stuff the message we want into the printf statement. We could call it a day now, but I am a very lazy coder… I do not want to be forced to put messages into the assert, sometimes I just want to assert.

    Of course it is possible to write an ASSERT(condition) and an ASSERTm(condition, message) macro, but did I mention I am a forgetful coder too? I’d much rather have a single ASSERT statement that can do both.

    The first thing that comes to mind is the fact I could do this easily with a function:

    void MyAssert(bool isOK, char const *message=””) {
    if ( !isOK ) {
     (void)printf(“ERROR!! Assert ‘%s’ failed on line %d “
      “in file ‘%s’\n%s\n”,
      __LINE__, __FILE__, message);
     __asm { int 3 } \
    }
    }

    So maybe if I declared another function:

    void NoAssert(bool isOK, char const *message=””) {}

    And then defined assert as:

    #ifndef NDEBUG
    # define ASSERT MyAssert
    #else
    # define ASSERT NoAssert
    #endif

    While this seems like a quick solution, I have completely lost my extra debug information! The line information is the same now for every assert… oh… the compiler substitutes __LINE__ with the actual line number it is compiling at that moment, and since we are making a function call – all line numbers lead to the MyAssert function!

    Alexandrescu demonstrates a great way around this problem [Alexandrescu]. (It is also a great article showing how you can take assertions to a higher level after this one, by making them throw exceptions!)

    #ifndef NDEBUG
    #define ASSERT \
    struct MyAssert { \
    MyAssert(bool isOK, char const *message=””) { \
     if ( !isOK ) { \
      (void)printf(“ERROR!! Assert failed in “ \
       “file ‘%s’\n%s\n”, __FILE__, message); \
       __asm { int 3 } \
      } \
     } \
    } myAsserter = MyAssert
    #endif

    For some reason my Visual C++ 7.1 compiler will not accept the __LINE__ macro next to the __FILE__ macro in the code above. The strange thing is that the __FILE__ macro works fine, but with __LINE__ it complains:

    error C2065: '__LINE__Var' : undeclared identifier

    It is never easy, but I do not want to give up at this point. Since the macro is expanded as a single line into the place where we are calling it, and since the compiler apparently has no objection to me assigning __LINE__ as a default parameter in a constructor, let's try again:

    #ifndef NDEBUG
    #define ASSERT \
    struct MyAssert { \
    int mLine; \
    MyAssert(int line=__LINE__) : mLine(line) {} \
    MyAssert(bool isOK, char const *message=””) { \
     if ( !isOK ) { \
      (void)printf(“ERROR!! Assert failed on “ \
       “line %d in file ‘%s’\n%s\n”, \
       MyAssert().mLine, __FILE__, message); \
      __asm { int 3 } \
     } \
    }\
    } myAsserter = MyAssert
    #endif

    Now that we have our line information back, we are nearly there; as soon as we add a second assert, the compiler complains that we are redefining the struct MyAssert! If only we could keep the struct declaration local… and again Alexandrescu shows us how [Alexandrescu]:

    #ifndef NDEBUG
    #define ASSERT \
    if ( false ) {} else struct LocalAssert { \
     int mLine; \
    LocalAssert(int line=__LINE__) : mLine(line) {} \
    LocalAssert(bool isOK, char const *message=””) { \
     if ( !isOK ) { \
      (void)printf(“ERROR!! Assert failed on “ \
       “line %d in file ‘%s’\n%s\n”, \
       LocalAssert().mLine, __FILE__, message); \
      __asm { int 3 } \
    } \
    } myAsserter = LocalAssert
    #else
    #define ASSERT \
    if ( true ) {} else struct NoAssert { \
    NoAssert(bool isOK, char const *message=””) {} \
    } myAsserter = NoAssert
    #endif

    There is a lot of fun to be had with macros and sometimes it is possible to create the wildest incantations with them [Niebler/Alexandrescu]. I hope you are convinced that despite the fact that they can be considered evil, there is something magical about them as well.

    As a final example I will show you how to create personal and customizable debug streams in the next article… all with macros.


    References

    [STL] – The Standard Template Library

    < comes standard with your compiler but this one is very portable>

    http://www.stlport.org

    [BOOST] – Boost C++ Libraries

    http://www.boost.org

    [ACE] – The ADAPTIVE Communication Environment

    http://www.cs.wustl/edu/~schmidt/ACE.html

    [Niebler] – Eric Niebler

    “Conditional Love: FOREACH Redux”

    http://www.artima.com/cppsource/foreach.html

    [Alexandrescu] – Andrei Alexandrescu

    Assertions

    http://www.cuj.com/documents/s=8248/cujcexp2104alexandr/

     

    Posted by Triany
    2011. 3. 14. 20:24

    출처:http://www.cplusplus.com/reference/iostream/istream/

    Output Stream

    ostream

    ostream objects are stream objects used to write and format output as sequences of characters. Specific members are provided to perform these output operations, which can be divided in two main groups:
    • Formatted output
      These member functions interpret and format the data to be written as sequences of characters. These type of operation is performed using member and global functions that overload the insertion operator (operator<<).
    • Unformatted output
      Most of the other member functions of the ostream class are used to perform unformatted output operations, i.e. output operations that write the data as it is, with no formatting adaptations. These member functions can write a determined number of characters to the output character sequence (put, write) and manipulate the put pointer (seekp, tellp).
    Additionaly, a member function exists to synchronize the stream with the associated external destination of characters: sync.

    The standard objects cout, cerr and clog are instantiations of this class.

    The class inherits all the internal fields from its parent classes ios_base and ios:

    Formatting information
    • format flags: a set of internal indicators describing how certain input/output operations shall be interpreted or generated. The state of these indicators can be obtained or modified by calling the members flags, setf and unsetf, or by using manipulators.
    • field width: describes the width of the next element to be output. This value can be obtained/modified by calling the member function width or parameterized manipulator setw.
    • display precision: describes the decimal precision to be used to output floating-point values. This value can be obtained/modified by calling member precision or parameterized manipulator setprecision.
    • fill character: character used to pad a field up to the field width. It can be obtained or modified by calling member function fill or parameterized manipulator setfill.
    • locale object: describes the localization properties to be considered when formatting i/o operations. The locale object used can be obtained calling member getloc and modified using member imbue.
    State information
    • error state: internal indicator reflecting the integrity and current error state of the stream. The current object may be obtained by calling rdstate and can be modified by calling clear and setstate. Individual values may be obtained by calling good, eof, fail and bad.
    • exception mask: internal exception status indicator. Its value can be retrieved/modified by calling member exceptions.
    Other
    • event function stack: stack of pointers to callback functions that are called when certain events occur. Additional callback functions may be registered to be called when an event occurs, using member function register_callback.
    • internal extensible arrays: two internal arrays to store long objects and void pointers. These arrays can be extended by calling member function xalloc, and references to these objects can be retrieved with iword or pword.
    • pointer to tied stream: pointer to the stream object which is tied to this stream object. It can be obtained/modified by calling member function tie.
    • pointer to stream buffer: pointer to the associated streambuf object. It can be obtained/modified by calling member function rdbuf.

    Public members


    Formatted output:

    Unformatted output:

    Positioning:

    Synchronization:

    Prefix/Suffix:

    Member functions inherited from ios


    Member functions inherited from ios_base




    istream

    class
    <istream>

    Input stream

    istream


    istream objects are stream objects used to read and interpret input from sequences of characters. Specific members are provided to perform these input operations, which can be divided in two main groups:
    • Formatted input
      These functions extract data from a sequence of characters that may be interpreted and formatted to a value of a certain type. These type of operation is performed using member and global functions that overload the extraction operator ().
    • Unformatted input
      Most of the other member functions of the istream class are used to perform unformatted input, i.e. no interpretation is made on the characters got form the input. These member functions can get a determined number of characters from the input character sequence (get, getline, peek, read, readsome), manipulate the get pointer i(ignore, seekg, tellg, unget) or get information of the last unformatted input operation (gcount).
    Additionaly, a member function exists to synchronize the stream with the associated external source of characters: sync.

    The standard object cin is an instantiation of this class.

    The class inherits all the internal fields from its parent classes ios_base and ios:

    Formatting information
    • format flags: a set of internal indicators describing how certain input/output operations shall be interpreted or generated. The state of these indicators can be obtained or modified by calling the members flags, setf and unsetf, or by using manipulators.
    • field width: describes the width of the next element to be output. This value can be obtained/modified by calling the member function width or parameterized manipulator setw.
    • display precision: describes the decimal precision to be used to output floating-point values. This value can be obtained/modified by calling member precision or parameterized manipulator setprecision.
    • fill character: character used to pad a field up to the field width. It can be obtained or modified by calling member function fill or parameterized manipulator setfill.
    • locale object: describes the localization properties to be considered when formatting i/o operations. The locale object used can be obtained calling member getloc and modified using member imbue.
    State information
    • error state: internal indicator reflecting the integrity and current error state of the stream. The current object may be obtained by calling rdstate and can be modified by calling clear and setstate. Individual values may be obtained by calling good, eof, fail and bad.
    • exception mask: internal exception status indicator. Its value can be retrieved/modified by calling member exceptions.
    Other
    • event function stack: stack of pointers to callback functions that are called when certain events occur. Additional callback functions may be registered to be called when an event occurs, using member function register_callback.
    • internal extensible arrays: two internal arrays to store long objects and void pointers. These arrays can be extended by calling member function xalloc, and references to these objects can be retrieved with iword or pword.
    • pointer to tied stream: pointer to the stream object which is tied to this stream object. It can be obtained/modified by calling member function tie.
    • pointer to stream buffer: pointer to the associated streambuf object. It can be obtained/modified by calling member function rdbuf.

    Public members


    Formatted input:

    Unformatted input:

    Positioning:

    Synchronization:

    Prefix/Suffix:

    Member functions inherited from ios


    Member functions inherited from ios_base

    Posted by Triany
    2011. 3. 14. 20:23
    p + 3

    ==

    p.operator+(3)

     
    class Point {
    private:
     int x, y;
    public:
     Point(int _x=0, int _y=0):x(_x), y(_y){}
     void ShowPosition();
     void operator+(int val); //operator+라는 이름의 함수
    };
    void Point::ShowPosition()
    {
     cout<<x<<"  "<<y<<endl;
    }
    void Point::operator+(int val)
    {
     x+=val;
     y+=val;
    }//operator+라는 이름의 함수

    int main(void)
    {
     Point p(3,4);
     p.ShowPosition();
     //p.operator +(10);
     p+10;
     p.ShowPosition();
     return 0;
    }


    <연산자를 오버로딩하는 방법>
    1. 멤버 함수에 의한 오버로딩
    2. 전역 함수에 의한 오버로딩


    1. 멤버함수에 의한 오버로딩

     
    class Point {
    private:
     int x, y;
    public:
     Point(int _x=0, int _y=0):x(_x), y(_y){}
     void ShowPosition();
     void operator+(int val); //operator+라는 이름의 함수
     Point operator+(const Point & p);
    };
    void Point::ShowPosition()
    {
     cout<<x<<"  "<<y<<endl;
    }
    void Point::operator+(int val)
    {
     x+=val;
     y+=val;
    }//operator+라는 이름의 함수

    Point Point::operator+(const Point & p)
    {
     Point temp(x+p.x, y+p.y);
     return temp;
    }

    int main(void)
    {
     Point p1(1, 2);
     Point p2(2, 1);
     Point p3=p1+p2;
     p3.ShowPosition();
     return 0;
    }




    2. 전역 함수에 의한 오버로딩
    클래스에 있는 private로 선언된 변수를 직접 접근하기 위해선,
    클래스 내에 friend 선언을 해 두어야 한다.

    <오버로딩이 불가능한 연산자>
    .              .*             ::                  ?:         sizeof


    ++p -> p.operator++()
    p++ -> p.operator++(int)
    Posted by Triany
    2011. 3. 9. 21:06

    C에서는 출력양식에서 prinf("%2d", a);
    이런 식의 출력양식이 있어서 출력할때 제법 깔끔했다.

    하지만, C++언어로 들어온뒤
    cout<<a;
    식으로 출력할때 %d와 같은 출력 형식을 지정하지 않은 것은 편했지만, 예쁘게(?) 출력이 안되는게 고민이었다.
    이때 해결책이 setw(int num) 함수다.ㅎ

    setw(int num)
    헤더 : #include <iomanip.h>

    가령
    cout<<setw(7)<<"Hey~"<<endl;
    라고 입력하게 되면,
    "Hey~   " 이렇게 3자리 공백과 함께 출력된다.

    잘만 사용하면 제법 깔끔해 보이는 프로그래밍을 할 듯 싶다.
    Posted by Triany
    2011. 3. 9. 19:39

    virtual 함수는,
    최종적으로 오버라이딩 한 함수를 제외하고 나머지 함수는 가려지게 된다.

    static binding : 컴파일하는 동안(컴파일-타임)에 호출될 함수가 결정. (호출될 함수가 이미 고정되어 있는것.)

    dynamic binding : 컴파일 하는 동안(컴파일-타임)에 호출될 함수가 결정되는 것이 아니라, 실행하는 동안(런-타임)에 호출될 함수가 결정된다. 포인터가 가리키는 객체가 무엇이냐에 따라서 그 문장이 호출되는 함수는 유동적이다.
    다형성의 한 예("모양은 같은데 형태는 다르다.")

     #include <iostream>
    using std::cout;
    using std::cin;
    using std::endl;

    class AAA
    {
    public:
     virtual void fct()
     {
      cout<<"AAA"<<endl;
     }
    };
    class BBB : public AAA
    {
    public:
     void fct()    //virtual 키워드를 삽입하지 않더라도 자동적으로 virtual void fct()화 됨.
     {
      cout<<"BBB"<<endl;
     }
    };

    class CCC : public BBB
    {
    public:
     void fct()
     {
      cout<<"CCC"<<endl;
     }

    };

    int main(void)
    {
     BBB b;
     b.fct(); //static binding
     AAA* a = new BBB;
     a->fct(); //dynaminc binding

     delete a;
     return 0;
    }




    ####virtual 함수를 사용하지 않은 예제결과와 비교해 볼것~!

     #include <iostream>
    using std::cout;
    using std::cin;
    using std::endl;

    class AAA
    {
    public:
     void fct()
     {
      cout<<"AAA"<<endl;
     }
    };
    class BBB : public AAA
    {
    public:
     void fct()
     {
      cout<<"BBB"<<endl;
     }
    };

    class CCC : public BBB
    {
    public:
     void fct()
     {
      cout<<"CCC"<<endl;
     }

    };

    int main(void)
    {
     BBB b;
     b.fct(); //static binding
     AAA* a = new BBB;
     a->fct(); //dynaminc binding

     delete a;
     return 0;
    }





    [오버라이딩 된 함수 호출하기]
    방법 : 범위 지정 연산자를 이용.
    a->AAA::fuct(); 의 방식으로 사용.
    Posted by Triany
    2011. 3. 7. 21:42

    <명시적인 것만을 허용!! explicit>
    =>묵시적인 호출을 허용하지 않는다.
    =>객체 생성관계를 분명히 하고자 하는 경우에 주로 사용.

     #include <iostream>
    using std::cout;
    using std::cin;
    using std::endl;

    class AAA
    {
    public:
     explicit AAA(int n)
     {
      cout<< "explicit AAA(int n)"<< endl;
     }
    };

    int main(void)
    {
     AAA a1=10; //묵시적으로 변환 -> AAA a1(10); //Compile Error!!!
     return 0;
    }



    <예외를 둔다! : mutable>
    =>const로 멤버함수가 상수화 되면 이 함수는 멤버 변수를 변경시키지 못한다.
    그러나 멤버변수가 mutable로 선언이 되면 상수화된 멤버 변수라 할지라도 데이터 변경이 가능해 진다!!

     #include <iostream>
    using std::cout;
    using std::cin;
    using std::endl;

    class AAA
    {
    private:
     mutable int val;
     int val2;
    public:
     void SetData(int a, int b) const
     {
      val1=a; //val1이 mutable이므로 가능!!!!
      val2=b; //Error!!!!
     }
    };

    int main(void)
    {
     AAA a1;
     a1.SetData(10, 20);
     return 0;
    }

    ,, mutable은 프로그램에 유연성을 제공한다는 장점이 있지만,,
    권장하지 않는다......!!

    출처: 열혈강의 c++


    Posted by Triany