Hello there!
I have the following problem:
I want to write a program that gets the time in the form hours:minutes via stdin, and then give output like this. The problem for me is: how do I split the input to two integers for hours and minutes?
I have been trying to find a solution for almost a hour. Every time I found code that didn't work for me, and that I didnt understand.
Please note: I'm just starting to learn C++. Please explain your answer extensively.
To add some information (can't find an edit button)
I have found solution using vectors, find_first_of and boost libaries. I just didn't understand.
Splitting numbers in strings to ints
Page 1 of 15 Replies - 431 Views - Last Post: 08 October 2012 - 06:18 AM
Replies To: Splitting numbers in strings to ints
#2
Re: Splitting numbers in strings to ints
Posted 07 October 2012 - 09:48 AM
#3
Re: Splitting numbers in strings to ints
Posted 07 October 2012 - 09:59 AM
Quote
I have been trying to find a solution for almost a hour. Every time I found code that didn't work for me, and that I didnt understand.
Quote
Please note: I'm just starting to learn C++.
Then I suggest you try to write your own solution. You will not learn anything by trying to "find" a solution. You learn programming by programming. So show us your best effort at solving this problem and we may be able to help point you in the right direction.
Jim
#4
Re: Splitting numbers in strings to ints
Posted 08 October 2012 - 04:54 AM
Well, Jim got me thinking. Eventually I found out about strncpy(). This is what I came up with:
That returns the first two characters of time[]. Now I have another question: how do I get the last two characters of time[]? Or to be more general: how do I get any part of an array? I can't figure this out.
int main()
{
char time[5], hour[2];
int hour_num;
cout << "give time"<<endl;
cin >> time;
cout << " "<<endl;
strncpy(hour,time,2);
hour[2]='\0';
cout << hour <<endl;
hour_num = atoi(hour);
cout << hour_num <<endl;
return 0;
}
That returns the first two characters of time[]. Now I have another question: how do I get the last two characters of time[]? Or to be more general: how do I get any part of an array? I can't figure this out.
#5
Re: Splitting numbers in strings to ints
Posted 08 October 2012 - 06:13 AM
Arrays start at 0, so the first three elements of time would be time[0], time[1], and time[2].
#6
Re: Splitting numbers in strings to ints
Posted 08 October 2012 - 06:18 AM
I suggest you start by studying the following links: Arrays, Character Sequences. I also suggest that instead of the C-string you use std::string. By using the string class you won't need to worry about not having enough size for your string, and you will have functions like substr() to help pick out a section of the string.
Jim
Jim
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote





|