[英]printing time to std::ostream
我刚刚开始阅读C ++教科书,但在本章末尾我遇到了一个编码问题。 这是一个问题:
编写一个程序,要求用户输入小时值和分钟值。 然后main()函数应将这两个值传递给类型void函数,该函数以下面的示例运行中显示的格式显示两个值:
输入小时数:9
输入分钟数:28
时间:9:28
到目前为止我的代码是:
#include <iostream>
using namespace std;
void time(int h, int m);
int main()
{
int hour, min;
cout << "enter the number of hours: ";
cin >> hour;
cout << "enter the number of minutes: ";
cin >> min;
string temp = time(hour, min);
cout << temp;
return 0;
}
void time(int h, int m)
{
string clock;
clock =
}
我现在在time(n, m)
函数中做什么?
谢谢。
您可以包含<iomanip>
并设置字段宽度和填充,以便正确打印9:01
类的时间。 由于函数time
应该只打印时间,因此可以省略构建和返回std::string
。 只需打印这些值:
void time(int hour, int min)
{
using namespace std;
cout << "Time: " << hour << ':' << setfill('0') << setw (2) << min << endl;
}
还要注意using namespace std;
写using namespace std;
在文件的开头被认为是不好的做法,因为它会导致一些用户定义的名称(类型,函数等)变得模糊不清。 如果你想避免使用std::
前缀,请使用using namespace std;
在小范围内,以便其他功能和其他文件不受影响。
该问题请求“一个类型的void函数,它以显示的格式显示两个值”,因此最简单和最正确的(因为它匹配所要求的)解决方案是:
void time(int h, int m)
{
cout << "Time: " << h << ":" << m << endl;
}
你的main()函数然后只需要做什么......
// ... prompt for values as before, then:
time(hour, min);
return 0;
}
然后回来。
第一次()应该返回一个std :: string。 要在time()中格式化字符串,可以使用std :: ostringstream(header sstream)。
例如:
std::string time(int hour, int minutes)
{
std::ostringstream oss;
oss << hour << ":" << minutes;
return oss.str();
}
编辑:当然,您也可以直接在时间(..)功能内打印小时和分钟。 或者您可以传递时间(..)函数也是一个流参数,让时间(..)在该流上打印出来。
你在main中的代码假设time
是一个string
方法,问题说明void
。 你的代码应该是:
#include <iostream>
using namespace std;
void time(int h, int m);
int main()
{
int hour, min;
cout << "enter the number of hours: ";
cin >> hour;
cout << "enter the number of minutes: ";
cin >> min;
// Now pass to your time method.
time(hour, min);
return 0;
}
void time(int h, int m)
{
cout << "Time: " << h << ':' << m << endl;
}
鲍勃是某人的叔叔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.