Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setw not working as expected

Tags:

c++

setw

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?

like image 791
granra Avatar asked Sep 26 '13 20:09

granra


2 Answers

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 << ' ';
like image 182
Dietmar Kühl Avatar answered Oct 16 '22 18:10

Dietmar Kühl


Following is correct way:

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

Ref :-this

like image 30
P0W Avatar answered Oct 16 '22 16:10

P0W