Time in string to int

Hello,
i have problem with converting time in string to int.
I have string="9:00-10:30" or anything else like "19:00-24:00"
and i want to get from this
int mins1 = mins of first time (540)
int mins2 = mins of second time (630)
some ideas ? I know i can get it with sscanf but i dont want to convert string time into char because this string is generated from 2d array. Also i trying getline but still i don't get right output
Use sscanf to read for numbers from the string:

1
2
3
4
5
6
char s[] = "9:00-10:30";
int h1, m1, h2, m2;
//... substitute all ':' and '-' with spaces
sscanf(s, "%d %d %d %d", &h1, &m1, &h2, &m2);
int mins1 = h1 * 60 + m1;
//... etc. 


Here is the description of more general problem, though I hope my example is clear enough itself:

http://codeabbey.com/index/task_view/modulo-and-time-difference
i know this way but i can't use it as i write... i have 2D array of strings
string arrayc[25][width]; and i when i write char s[20] = arrayc[i][5] it output error.
arrayc[i][5] = "9:00-10:30"
"array must be initialized with a brace-enclosed initializer|"
I'm sorry but I do not understand your problem. What about 2D arrays? Do you use "string" instead of "char[]"? It looks you'd better put more of your code here.
when i write char s[20] = arrayc[i][5] it output error.

What about
1
2
char s[20];
strcpy(s, arrayc[i][5]);

(But std::string is easier still).
As for the original question on "9:00-10:30" or "19:00-24:00"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    
    string s = "9:00-10:30";

    istringstream ss(s);
    int hh, mm, hh2, mm2;
    char c1, c2, c3;

    ss >> hh >> c1 >> mm >> c2 >> hh2 >> c3 >> mm2;

    if (ss && c1==':' && c2=='-' && c3== ':')
    {
        cout << "time from: " << hh << ':' << mm
             << " to " << hh2 << ':' << mm2 << endl;
    }
    else
    {
        cout << "data error: " << s << endl;
    }

Once you have hours and minutes, conversion to just minutes is simple enough.

There are other approaches, you could use substrings and atoi() co convert from c-string to int - there are many ways.
Last edited on
Topic archived. No new replies allowed.