关闭

学习笔记_setfill和setw

305人阅读 评论(0) 收藏 举报
分类:

1、setw()接受整数参数,设置输出域宽.

2、setfill()接受字符参数,用于指定当输出域宽大于实际输出域宽时所需的填充字符.

Time.h
#ifndef TIME_H
#define TIME_H

//Time class definition
class Time
{
public:
    Time();
    void setTime(int, int, int);  //set hour, minute and second
    void printtUniversal();       //print time in universal-time format
    void printStandard();         //print time in standard-time format
private:
    int hour;
    int minute;
    int second;
};

Time.cpp
#include <iostream>
#include <iomanip>
#include "Time.h"
using namespace std;

Time::Time()
{
    hour = minute = second = 0;
}

void Time::setTime(int h, int m, int s)
{
    hour = (h >= 0 && h <= 24) ? h : 0;
    minute = (minute >= 0 && minute <= 60) ? minute : 0;
    second = (second >= 0 && second <= 60) ? second : 0;
}

void Time::printtUniversal()
{
    cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second;
}

void Time::printStandard()
{
    cout << ((hour == 12 || hour == 0) ? 12 : hour % 12) << ":" << setfill('0') << setw(2) << minute << ":" << setw(2) << second << (hour < 12 ? " AM" : " PM");
}

Main.cpp
#include <iostream>
#include"Time.h">
using namespace std;

int main()
{
    Time t;
    cout << "The initial universal time is ";
    t.printtUniversal();
    cout << "\nThe initial standard time is ";
    t.printStandard();

    t.setTime(13, 27, 6);

    cout << "\n\nUniversal time after setTime is ";
    t.printtUniversal();
    cout << "\nStandard time after setTime is ";
    t.printStandard();

    t.setTime(99, 99, 99);

    cout << "\n\nAfter attemping invalid settings:" << "\nUniversal time: ";
    t.printtUniversal();
    cout << "\nStandard time: ";
    t.printStandard();
    cout << endl;
    system("pause");
}
结果
The initial universal time is 00:00:00
The initial standard time is 12:00:00
Universal time after setTime is 13:27:06
Standard time after setTime is 1:27:06 PM
After attempting invalid settings:
Universal time: 00:00:00
Standard time: 12:00:00 AM

通过结果可以看出,在printUniversal和printStandard中,使用setfill设置填充字符为‘0’,因此当minute为2时,将会显示02。若实际输出填满了setw指定的域宽,那么就不会显示填充字符。

note:一旦setfill指定了填充字符,该字符将应用在后续值的显示中。也就是说,setfill是一个“黏性”设置,但setw是一个“非粘性”设置,其只对紧接着显示的值起作用。对于粘性设置,当不需要时应恢复,否则可能会出现格式错误。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32471次
    • 积分:471
    • 等级:
    • 排名:千里之外
    • 原创:13篇
    • 转载:16篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论