gpt4 book ai didi

c++ - 如何在 C++ 中正确使用 setfill()?

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:08 29 4
gpt4 key购买 nike

所以我已经解决这个问题一段时间了,在成员的帮助下,我快完成了。我的最后一个问题在上面。

如有必要,我需要将 cout 时间格式化为 01:01:01,但是,我的输出是 1:1:1

问题出在这里:

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

这是完整的代码。

#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;

}

任何解决此问题的见解将不胜感激。如果您需要更多信息,请询问。

最佳答案

您还需要调用 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;
}

关于c++ - 如何在 C++ 中正确使用 setfill()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13340891/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com