I'm trying to print time in hh:mm format but when the time is like 01:01 it prints as 1:1. Here's my code:

void output(int hour, int min, char ampm){
    cout << setw(2) << setfill('0') << "The time is: " << hour << ":" << min << " ";

    if(ampm == 'P'){
        cout << "PM";
    }
    else if (ampm == 'A'){
        cout << "AM";
    }
}

As I understand it, this should work. I include iomanip. Can you see anything wrong with it?

有帮助吗?

解决方案

The width is a special formatting setting: While all other formatting flags are stick, the width() will be reset by each output operator (well, you can have user-defined output operators which don't reset the width() but doing so would not follow the normal style). That is, you need to set the width immediately prior to the output that should be affected:

std::cout << std::setfill('0')
          << std::setw(2) << hour << ':'
          << std::setw(2) << min << ' ';

其他提示

Following is correct way:

 cout<<""The time is: ";
 cout << setfill('0') <<setw(2) << hour << ":" <<setw(2) << min << " ";

Ref :-this

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top