zoukankan      html  css  js  c++  java
  • C++几种格式控制输出输入方法

    (A)用流成员函数进行输入输出格式控制 instance:

    #include <iostream>
    using namespace std;
    
    int main()
    {
    	cout<<"-----------1-----------"<<endl;
    	cout.width(10);
    	cout<<123<<endl;
    	cout<<"-----------2-----------"<<endl;
    	cout<<123<<endl;
    
    	cout<<"-----------3-----------"<<endl;
    	cout.fill('&');
    	cout.width(10);
    	cout<<123<<endl;
    
    	cout<<"-----------4-----------"<<endl;
    	cout.setf(ios::left);
    	cout<<123<<endl;
    
    	cout<<"-----------5-----------"<<endl;
    	cout.precision(4);
    	cout<<123.45678<<endl;
    
    	cout<<"-----------6-----------"<<endl;
    	cout.setf(ios::fixed);
    	cout<<123.45678<<endl;
    
    	cout<<"-----------7-----------"<<endl;
    	cout.width(15);
    	cout.unsetf(ios::fixed);
    	cout.setf(ios::scientific);
    	cout<<123.45678<<endl;
    
    	cout<<"-----------8-----------"<<endl;
    	int a  = 21;
    	cout.setf(ios::showbase);
    	cout.unsetf(ios::dec);
    	cout.setf(ios::hex);
    	cout<<a<<endl;
    	return 0;
    }
    

     说明:状态标志在类ios中被定义成枚举值,所以在引用时要在前面加上“ios::”,在使用setf()函数设置多项标志时,中间应该用或运算符“ | ”分隔开。

    (B)使用预定义的操纵符进行输入输出格式控制 instance:

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main()
    {
    	cout<<setw(10)<<123<<567<<endl;
    	cout<<setiosflags(ios::scientific)<<setw(20)<<setfill('$')<<123.4566778<<endl;
    	return 0;
    }
    

    使用ios类中的成员函数进行输入输出格式控制时,每个函数的调用需要写一条语句,而且不能将他们直接嵌入到输入输出语句中去,这样使用很不方便。使用预定义操纵符可以解决不方便的问题。

    (C)使用用户自定义的操纵符进行输入输出格式控制 instance:

    #include<iostream>
    #include<iomanip>
    using namespace std;
    
    ostream & output(ostream & stream)
    {
    	stream.setf(ios::left);
    	stream<<setw(10)<<hex<<setfill('&');
    	return stream;
    }
    int main()
    {
    	cout<<123<<endl;
    	cout<<output<<123;
    	return 0;
    }
    

    这里只提供输出自定义操纵。

  • 相关阅读:
    MySQL表的四种分区类型
    微信开发配置(Yii框架下的开发)
    一道编程题—输出字符串内重复的数字
    无序数组内查找指定值(快速查找)
    指针
    chmod
    cookie和session的区别
    使用keytool生成证书
    人大金仓修改最大连接数
    数据库链接地址
  • 原文地址:https://www.cnblogs.com/jiaoluo/p/3443835.html
Copyright © 2011-2022 走看看