C++标准输入输出流

                                             
 
                C++语言系统为实现数据的输入和输出定义了一个庞大的类库,包括的类主要有ios,istream,           ostream,ifstream,ofstream,fstream,ofstream,fstream,istrstream,ostrstream,strstream等,其中ios为根基类。
C++三种设置输入输出格式的方式

        (1)输入/输出流枚举常量;
            访问的方法很简单,只要在每个枚举类型常量加上iOS::前缀就可以设置相应的格式。我们常用的枚举常量有13个,分别为skipws,left,right,intrenal,dec,oct,hex,showbase,showpoint,uppercase,showpos,scientific,fixed。
        (2)输入/输出流的内部函数;
              下面给出一些输入/输出流格式控制的内部函数:
         函数形式                                                           功能说明
        int  bad()                                                 操作出错时返回非0 值
        int eof( )                                                      读取到流最后的文件结束符时返回非0值
        int fail ( )                                                      操作失败时返回非零值
        int  clear( )                                    清除bad,eof,和fail所对应的标志状态,使之恢复正常状态0,使good标志为1 

        int p recision( )                                     返回浮点数输出精度,即输出的有效数字的位数
              ps: 此处例举并不全,还有要补充的。
        (3)输入/输出流格式控制操作符;
            在使用数据输入/输出的格式控制的一种等简单的方法,需要添加头文件 #include<iomanip>。使用这些操作符不需要调用成员函数,只要把它们做为插入操作符 << 或 >>的输出/输入对象即可。
            包含有 dec,oct,hex,ws,endl,ends,flush,setiosflags(long f)......
例1:简单的编写一个程序:从键盘输入一个十进制数,将该数分别转换成十进制,八进制,十六进制输出到屏幕上。
#include <iostream>
#include <iomanip>
using namespace std;


int main()
{
    int n = 0;
    cout << "input a decimal number  " ;
    cin >> n;

    cout.setf(ios::dec);
    cout << "you input decimal number is " << n << endl;
    cout.unsetf(ios::dec);//清除十进制格式

    cout.setf(ios::oct);
    cout << "converted to octal number is " << n << endl;
    cout.unsetf(ios::oct);//清楚八进制格式

    cout.setf(ios::hex);
    cout << "converted to hex number is " << n << endl;
    cout.unsetf(ios::hex);//清楚十六进制格式
    return 0;
}

输出结果如下:
[root@localhost review]# vim demo1.c
[root@localhost review]# g++ demo1.c -o demo1
[root@localhost review]# ./demo1
input a decimal number  456
you input decimal number is 456
converted to octal number is 710
converted to hex number is 1c8
例2:
****************************************************
Funcion List: 输入一个char型数,并将其转化为十进制,八进制,十六进制数显示
*****************************************************/
#include <iostream>
using namespace std;
#include <iomanip>

int main()
{
    char n;
    cout << "please input a character:";
    cin >> n;

    cout << "the decimal digital number is" << dec << (static_cast<int>(n))<<endl;

    cout <<"convertrd to octal number is" << oct << (static_cast<int>(n))<<endl;
    cout << "converted to hexdecital number is" << hex << (static_cast<int>(n))<<endl;
    return 0;
}

输出结果如下:
[root@localhost review]# vim demo2.cpp
[root@localhost review]# g++ demo2.cpp -o demo2
[root@localhost review]# ./demo2
please input a character:a
the decimal digital number is97
convertrd to octal number is141
converted to hexdecital number is61

猜你喜欢

转载自blog.csdn.net/AltarS/article/details/80008804