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;
    }
    

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

  • 相关阅读:
    Uncaught DOMException: Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document. 打包vue dist到外网,无法访问
    linux find 命令
    CentOS提示 Failed to set locale, defaulting to C的解决方法
    JSP页面上添加Fckeditor
    对自己成为程序员的要求
    数组举例
    Java中构造方法被别封装后的调用
    JS读取/创建本地文件及目录文件夹的方法
    初学SSH(struts+spring+hibernate)的纠结问题
    POI Excel文件XSSF导入知识点
  • 原文地址:https://www.cnblogs.com/jiaoluo/p/3443835.html
Copyright © 2011-2022 走看看