cout 格式化输出

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

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

   首先要引入头文件

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

    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 <'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 : " <// 21 : 8 进制
    std::cout <<"dec : " <// 17 : 10 进制
    std::cout <<"hex : " <// 11 : 16 进制
    std::cout <<"hex : " <17.01 << std::endl ;        // 17.01 : 不受影响

 

 

你可能感兴趣的:(cout 格式化输出)