2012-11-12 2 views
0

저는 지금 당분간이 문제를 다루었으며 회원들의 도움을 받아 거의 끝났습니다. 이것에 대한 나의 마지막 질문은 위에 있습니다. 1 : 1C++에서 setfill()을 제대로 사용하려면 어떻게해야합니까?

문제는 여기에 있습니다 :

std::ostream& operator<< (ostream& os, const MyTime& m) 
{ 
    os << setfill('0') << m.hours << ":" << setfill ('0') << m.minutes << ":" << setfill ('0') << m.seconds; 
    return os; 
} 

이 전체이다, 그러나, 내 출력이 1 필요한 경우

나는 1시 1분 1초에 COUT 시간을 포맷해야 암호.

#include <iostream> 
#include <cstdlib> 
#include <cstring> 
#include <iomanip> 


using namespace std; 
struct MyTime { int hours, minutes, seconds; }; 
MyTime DetermineElapsedTime(const MyTime *t1, const MyTime *t2); 

const int hourSeconds = 3600; 
const int minSeconds = 60; 
const int dayHours = 24; 
const char zero = 0; 

MyTime DetermineElapsedTime(const MyTime *t1, const MyTime *t2) 
{ 
    long hourDiff = ((t2->hours * hourSeconds) - (t1->hours * hourSeconds)); 
    int timeHour = hourDiff/hourSeconds; 
    long minDiff = ((t2->minutes * minSeconds) - (t1->minutes * minSeconds)); 
    int timeMin = minDiff/minSeconds; 
    int timeSec = (t2->seconds - t1 -> seconds); 
    MyTime time; 
    time.hours = timeHour; 
    time.minutes = timeMin; 
    time.seconds = timeSec; 
    return time; 
} 

std::ostream& operator<< (ostream& os, const MyTime& m) 
{ 
    os << setfill('0') << m.hours << ":" << setfill ('0') << m.minutes << ":" << setfill ('0') << m.seconds; 
    return os; 
} 

int main(void) 
{ 
    char delim1, delim2; 
    MyTime tm, tm2; 
    cout << "Input two formats for the time. Separate each with a space. Ex: hr:min:sec\n"; 
    cin >> tm.hours >> delim1 >> tm.minutes >> delim2 >> tm.seconds; 
    cin >> tm2.hours >> delim1 >> tm2.minutes >> delim2 >> tm2.seconds; 

    if (tm2.hours <= tm.hours && tm2.minutes <= tm.minutes && tm2.seconds <= tm.seconds) 
     { 
      tm2.hours += dayHours; 
     } 
    cout << DetermineElapsedTime(&tm, &tm2); 


    return 0; 

} 

이 문제를 해결하기위한 모든 통찰력은 크게 감사하겠습니다. 더 자세한 정보가 필요하면 부탁하십시오.

답변

6

setw을 호출하여 스트림에 출력을 채워야한다는 것을 알릴 수 있습니다. setfill과 대비하여 setw은 다음 출력에만 적용됩니다.

std::ostream& operator<< (ostream& os, const MyTime& m) 
{ 
    return os << setfill('0') << setw(2) << m.hours << ":" 
       << setw(2) << m.minutes << ":" 
       << setw(2) << m.seconds; 
} 
+0

매우 좋습니다. 고마워. – user1781382

관련 문제