二級C++輸入輸出流:屏幕輸出

字號:

1、使用預定義的插入符:
    最一般的屏幕輸出是將插入符作用在流類對象 cout 上。
    例 1 : #include
    void main()
    {
    char *str=”string”;
    cout<<”the string is:”<    cout<<”the address is:”<<(void*) str<    }
    執(zhí)行結果: The string is:string
    the address is:0x00416d50
    注意:⒈ cout<    ⒉ cout<<(void*(s)) 或 cout<<(void*)s; 功能是輸出字符指針的地址值。
    2、使用成員函數 put() 輸出一個字符:
    格式: cout.put(char c)
    cout.put(const char c)
    功能:提供一種將字符送進輸出流的方法。
    例如: char c='m';
    cout.put( c); // 顯示字符 m.
    例 2 :分析下列程序的輸出結果:
    #include
    void main()
    {
    cout<<'a'<<','<<'b'<<'\n';
    cout.put(‘a').put(‘,').put(‘b').put(‘\n');
    char c1='A',c2='B';
    cout.put(c1).put(c2).put(‘\n');
    }
    結果: a,b
    a,b
    AB
    從該程序中可以看出,使用插入符( << )可以輸出字符,使用 put() 函數也可以輸出字符,但是集體使用格式不同。
    Put() 函數的返回值是 ostream 類的對象的引用。
    3 、使用成員函數 write() 輸出一個字符串。
    • 格式: cout.write(const char *str,int n)
    • 功能:將字符串送到輸出流。
    例 3 : #include
    #include
    void PirntString(char *s)
    {
    cout.write(s,strlen(s)).put(‘\n');
    cout.write(s,6)<<”\n”;
    }
    void main()
    {
    char str[]=”I love C++”;
    cout<<”the string is:”<    PrintString(str);
    PrintString(“this is a string”);
    }
    結果: the string is:I love C++
    I love C++
    I love
    This is a string
    This I
    說明:該程序中使用了 write() 函數輸出顯示字符??梢钥闯觯梢燥@示整個字符串的內容,也可以顯示部分字符串的內容。