1

So, I have to make the following program:

I input two "clocks", in format HH:MM, and I have to check the difference between them in minutes and output it. Then I have to check which time has bigger size, in minutes, and output which time is bigger or if they are equal.

So, I've done this:

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    string a, b, c, d;
    int a_min, b_min;

    getline(cin, a, ':');
    cin >> b;

    getline(cin, c, ':');
    cin >> d;

    a_min = atoi(a.c_str()) * 60 + atoi(b.c_str());

    b_min = atoi(c.c_str()) * 60 + atoi(d.c_str());

    if (a_min > b_min){
        cout << "Razlikata iznesuva " << a_min - b_min << " minuti" << endl;
        cout << "Pogolemo e prvoto vreme" << endl;
    }
    else if (b_min > a_min){
        cout << "Razlikata iznesuva " << b_min - a_min << " minuti" << endl;
        cout << "Pogolemo e vtoroto vreme" << endl;
    }
    else if (a_min == b_min){
        cout << "Vreminjata se isti" << endl;
    }
    return 0;
}

But when you input HH:MM, I have a ":" between the HH and MM, therefore I can't get the numbers simply, so I need help how to get hours and minutes and convert them (conversion should be easy I guess) or if there's alternative and better method for this?

4

3 回答 3

2
  1. You should be reading NUMBERS, not strings. Numbers are read until non-digit, so will stop at ::

    char dummy;
    int hour, minute;
    cin >> hour >> dummy >> minute;
    // check dummy == ':'
    
  2. Strings are read until whitespace. And the whitespace is not skipped unless you've set skipws. However there is a function that allows reading string until specific separator:

    string hour, minute;
    getline(cin, hour, ':'); // this will eat the `:`
    cin >> minute; // assuming whitespace or eof after this
    // check the values, that you didn't cross eof and such.
    
于 2013-10-21T14:23:24.553 回答
1

Use a std::istringstream to do the parsing for you; this expects time stamps in 24-hours format:

static unsigned int minutesSinceMidnight( const std::string &timeStamp )
{
    unsigned int hours, minutes;
    char colon;
    std::istringstream( timeStamp ) >> hours >> colon >> minutes;
    return hours * 60 + minutes;
}

You can then compare two time stamps easily and also tell how many minutes they are apart.

于 2013-10-21T14:20:29.463 回答
0

Something like this:

int h,m;
char separator;
cin >> h >> separator >> m;
if(separator == ':' && h>=0 && h < 24 && m >=0 && m < 60)
{
  // you have a correct hour
}
于 2013-10-21T14:13:06.987 回答