有关C++中的流操纵算子

来源:互联网 发布:轻淘客 登录淘宝联盟 编辑:程序博客网 时间:2024/06/14 00:09

C++提供了大量的用于执行格式化输入/输出的流操纵算子。流操纵算子提供了许多功能,如设置域宽、设置精度、设置和清除格式化标志、设置域填充字符、刷新流、在输出流中插入换行符并刷新该流、在输出流中插入空字符、跳过输入流中的空白字符等等。下面几节要介绍这些特征。

1.setbase(int _base):以进制基数b为输出整数值,支持将整数按照_base进制格式进行输出,使用setbase或者其他的任何参数化的流操纵算子都必须在程序中包含iomainp这个头文件,一旦设置流输出整数的基数,流的基数就保持不变,直到遇到新的设置整数基数的算子。

下面举个例子说明:

#include<iostream>#include<iomanip>using namespace std;int main(){    int a = 10 ;    //以八进制格式输出    cout << "in octal is:\n" ;    cout << setbase(8) << a << endl;    cout << oct << a << endl;    //以十进制格式输出    cout << "in decminal is:\n" ;    cout << setbase(10) << a << endl;    cout << dec << a << endl;    //以十六进制格式输出    cout << "in hexadecimal is:\n" ;    cout << setbase(16) << a << endl;    cout << hex << a << endl;    return 0;}

2.setprecision(int n)和precision函数:用于控制小数点后的有效数字位数,一旦设置了精度,该精度对cout中其后的所有的输出操作都有效,直到遇到下一个流操纵算了重新设置精度为止。以无参数的方式调用函数precision,可以返回当前设置的精度。

例:

#include<iostream>#include<iomanip>#include<math.h>using namespace std;int main(){    double d = log(2.0) ;    cout << "current precision:" << cout.precision() << endl;    int places ;    cout << "log(2) with precisions 1-9.\n"         << "Precision set by the precision member function:" << endl;    for(places = 1 ;places <10 ;++places)    {        cout.precision(places) ;        cout << d << "\n" ;    }    cout << "\nPrecision set by the setprecision manipulator:\n";    for(places = 1 ;places < 10 ;++places)    {        cout << setprecision(places) << d << "\n" ;    }    return 0;}

3.设置域宽的流操纵算子

函数width可以实现对当前域宽(即输入输出的字符数)的设置,该函数同时返回上次设置的域宽,如果输出的数据所需的宽度比设置的域宽小,则空位用填充字符(默认为空格)填充。如果被显示的数据所需的宽度比设置的域宽大,则系统会自动突破宽度限制,输出所有位,域宽设置仅对下一行流读入或流插入抄做有效,在一次操作完后被置0,流操纵算子setw也可以用来设置域宽。例:

width:输入操作提取字符串的最大宽度比定义的域宽小1,这是因为在输入的字符串后面必须加上一个空字符。

#include<iostream>#include<iomanip>using namespace std;#define WIDTH 5int main(){    int w = 4 ;    char s[WIDTH+1] ;    cin.width(WIDTH);    while(cin >> s)    {        cout.width(w++);    //每次输出过后,让输出域宽自加1        cout << s<< endl;        cin.width(WIDTH);   //设置接受4个字符    }    return 0;}
4.设置填充字符(fill、setfill)

首先要进行字符填充,那么你就得设置域宽,设置了域宽过后,你才能进行字符的填充,fill函数用于返回当前的填充字符,设置了填充字符过后,对设置了域宽的所有的cout都有效,直到遇到下一个流操作算子重新设置为止。例:

#include<iostream>#include<iomanip>using namespace std;int main(){    int a = 10 ;    cout << "current fill chracter:" << cout.fill() << endl ;    cout << setw(20) << setfill('0') << a << endl;    cout << "current fill chracter:" << cout.fill() << endl ;    cout << setw(10) << 9 << endl;;    cout << setfill(' ') ;    cout << setw(10) << 1 << endl;    return 0;}



原创粉丝点击