[英]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.