Combining common code in functions as individual function in C++? -
i'm working on application in c++, , small part of involves appending date , time in array values, i've created couple of functions these values , make them more user-friendly. there's common chunk of code between 2 functions, , can't remember life of me how stick in it's own function , have work currently. full code below:
// getdateandtime.cpp : defines entry point console application. // #include "stdafx.h" #include <iostream> #include <ctime> #include <sstream> using namespace std; string gettime(); string getdate(); int main() { string thetime = gettime(); string thedate = getdate(); cout << "it " << thetime << " on " << thedate << endl; return 0; } string gettime() { // define variables string strhour; string strmin; // local time time_t now; struct tm nowlocal; = time(null); nowlocal = *localtime(&now); int hour = nowlocal.tm_hour; int min = nowlocal.tm_min; // send hour value string stringstream sshour; sshour << hour; if (hour >= 0 && hour <= 9) { strhour = "0" + sshour.str(); } else { strhour = sshour.str(); } // send min value string stringstream ssmin; ssmin << min; if (min >= 0 && min <= 9) { strmin = "0" + ssmin.str(); } else { strmin = ssmin.str(); } string curtime = strhour + ":" + strmin; return curtime; } string getdate() { // define variables string strday; string strmonth; string stryear; // local time time_t now; struct tm nowlocal; = time(null); nowlocal = *localtime(&now); int day = nowlocal.tm_mday; int month = nowlocal.tm_mon + 1; int year = nowlocal.tm_year + 1900; // send day value string stringstream ssday; ssday << day; if (day >= 1 && day <= 9) { strday = "0" + ssday.str(); } else { strday = ssday.str(); } // send month value string stringstream ssmonth; ssmonth << month; if (month >= 1 && month <= 9) { strmonth = "0" + ssmonth.str(); } else { strmonth = ssmonth.str(); } // send year value string stringstream ssyear; ssyear << year; stryear = ssyear.str(); string curdate = strday + "/" + strmonth + "/" + stryear; return curdate; }
the code block in question 1 commented "get local time". i'd appreciate @ all! thank you!
you can define function called getlocaltime
. function these 4 lines contains. in both gettime
, getdate
you'll call it.
Comments
Post a Comment