문제

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