I am trying to take an input formatted like 11-5-2008, 01-01-2020 or 1-1-2020 and turn that into three integer values, one for the day, month and year.
I am trying to use a loop to take the first number (or two) and place it into a new integer variable and to break when it finds a hyphen, remove the hyphen and repeat the process two times.
I understand how to output what I want to but I don't know how to store the getchar outputs into an int variable or how to tell it to stop when it recognizes '-'.
I was hoping to use something like this to turn the string into just integers, but I cannot figure out how to get this to work.
1 2 3 4 5 6 7
|
for (int i = 0; i < strLength; i++)
{
if (string1[i] == '-')
{
string1.erase(string1[i]+0);
}
}
|
This is basically what I have so far. Not that useful but this is about what I understand to.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
string string1;
int month;
int day;
int year;
cout<<"what date?" << endl;
getline(cin, string1);
month = stoi(string1);
int strLength = string1.length();
for (int i = strLength; i > (strLength-5); i--)
{
string1.erase(string1.end()-1);
}
|
I can think of multiple approaches, but don't know how to facilitate any of them.
I can remove the hyphens so it is just a string of numbers but I am not sure how I would turn that into a 10 character string to extract three precise integers from it with single digit months and days.
I can do a loop to add a string to a new string/int and break whenever I see a hyphen. I think this is what was intended.
I can do a sort of combination like my current code. I can stoi the month value really easy and remove the year value. If I could store that year to an integer before removing it then I would be left with 1-1 or 01-01 and I still don't know how to get rid of the first two or three digits and break when the hyphen is found.