Skip to content

Instantly share code, notes, and snippets.

@ernado
Created September 9, 2012 22:01
Show Gist options
  • Select an option

  • Save ernado/3687570 to your computer and use it in GitHub Desktop.

Select an option

Save ernado/3687570 to your computer and use it in GitHub Desktop.
Lab 01
#include <iostream>
#include <string>
#include "riostream.h"
#include <sstream>
using namespace std;
// returns <number> plural form from (<one>,<few>,<many>)
string pluralNumber(int number, string one, string few, string many)
{
// modulo - last digit of number
int modulo = number % 10;
// one
if (number == 1 || modulo == 1)
return one;
// number∈(1;5) or n∈(20;+inf) and modulo∈(1;5) - few
if ((number > 1 && number < 5) || (number > 20 && modulo > 1 && modulo < 5))
return few;
//else - many
return many;
}
// returns time of the day, depending on the <hours>
string getDayTime(int hours)
{
string daytime;
if (hours > 12)
{
// pm
hours -= 12;
if (hours < 6)
daytime = " дня";
else
daytime = " вечера";
}
else
{
// am
if (hours < 6)
daytime = " ночи";
else
daytime = " утра";
if (hours == 12)
daytime = " дня";
if (hours == 0)
hours = 12;
}
return daytime;
}
// checks format (hh:mm) and range (h∈[0;24), m∈[0;60)) of time in <s>
// if correct - returs 1, else - 0
bool isCorrectTime(string s)
{
// format
if (s.length()!=5)
return false;
if ( !( s[2] == ':'
&& isdigit(s[0])
&& isdigit(s[1])
&& isdigit(s[3]) && isdigit(s[4]) ) )
return false;
// parse minutes and hours
int h = atoi(s.substr(0,2).c_str()); // hours
int m = atoi(s.substr(3,5).c_str()); // minutes
// check range (h∈[0;24), m∈[0;60))
if ((h >= 0) && (m >= 0) && (h < 24) && (m < 60))
return true;
else
return false;
}
// returns time <s> in verbal form
// format: hh:mm
string parseToVerbalTime(string s)
{
stringstream stream;
string h = s.substr(0,2);
string m = s.substr(3,5);
int hours = atoi(h.c_str());
int minutes = atoi(m.c_str());
string daytime = getDayTime(hours);
// check for midnight or 12:00
if (minutes == 00)
if (hours == 12)
return "полдень";
else if (hours == 00)
return "полночь";
if (hours > 12)
hours-=12;
stream << hours; // convert int => string
h = stream.str();
stream.clear(); stream.str(""); // reset stream
stream << minutes; // convert int => string
m = stream.str();
return h + " " + pluralNumber(hours, "час", "часа", "часов") + " "
+ m + " " + pluralNumber(minutes, "минута", "минуты", "минут") + " " + daytime;
}
int main()
{
string input;
cout << "Введите время в формате чч:мм" << endl;
while (1)
{
cin >> input;
if (isCorrectTime(input))
break; // continue to process the correct user input
else
cout << "Время введено неверно, попробуйте еще раз" << endl;
}
cout << "Время: " << parseToVerbalTime(input) << endl;
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment