zoukankan      html  css  js  c++  java
  • cout 格式化输出

       一直习惯于C语言的printf函数来打印,突然有一天要用cout来打印,发现有点不适应。

       原来cout也是有格式化输出的。

       首先要引入头文件

    #include<iostream> // 在使用setf等库函数时使用
    #include<iomanip>  // 在使用流操纵算子时使用

        cout可以用setw来设置字符串的长度,不足的话,可以用setfill来设置填充

       string str = "1401435919";
    
        time_t ti = atoi(str.c_str());
    
        struct tm*  p = gmtime(&ti);
    
        // printf的写法
        printf("%04d/%02d/%02d %02d:%02d:%02d\n", 
              1900 + p->tm_year,
              1 + p->tm_mon,
              p->tm_mday,
              8 + p->tm_hour,
              p->tm_min,
              p->tm_sec);
    
        // cout的写法
        std::cout <<std::setfill('0') ;
        std::cout << std::setw(4) << 1900 + p->tm_year << "/" 
            << std::setw(2) << 1 + p->tm_mon << "/" 
            << std::setw(2) << p->tm_mday << " "
            << std::setw(2) << 8 + p->tm_hour << ":"
            << std::setw(2) << p->tm_min << ":" 
            << std::setw(2) << p->tm_sec << std::endl;

    输出结果: 2014/05/30 15:45:19

     以指定的进制输出

        int ival = 17; 
        std::cout <<"oct : " <<oct <<ival << std::endl ;        // 21 : 8 进制
        std::cout <<"dec : " <<dec <<ival << std::endl ;        // 17 : 10 进制
        std::cout <<"hex : " <<hex <<ival << std::endl ;        // 11 : 16 进制
        std::cout <<"hex : " <<hex <<17.01 << std::endl ;        // 17.01 : 不受影响
    高山流水,海纳百川!
  • 相关阅读:
    SpringBoot exception异常处理机制源码解析
    集群时间同步
    VMware 克隆的相关设置
    MySQL安装
    MogliFS与spring mvc结合简单示例
    MogileFS与spring结合
    MogileFS表说明
    使用Maven编译项目遇到——“maven编码gbk的不可映射字符”解决办法
    IAT HOOK 简单实现
    进程加载_模块隐藏
  • 原文地址:https://www.cnblogs.com/ahcc08/p/3762839.html
Copyright © 2011-2022 走看看