Jay*_*Jay 3 c++ string time iostream cout
我刚刚开始阅读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 =
}
Run Code Online (Sandbox Code Playgroud)
我现在在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;
}
Run Code Online (Sandbox Code Playgroud)
另请注意,using namespace std;在文件开头写入被认为是不好的做法,因为它会导致一些用户定义的名称(类型,函数等)变得模糊不清.如果您想避免std::使用前缀,请using namespace std;在小范围内使用,以便其他功能和其他文件不受影响.
| 归档时间: |
|
| 查看次数: |
762 次 |
| 最近记录: |