I have recently started a IT degree, but I have been programming for years. Never programmed in C++ though.
What the program must do: Get user input for current date (in format dd/mm/yyyy) and get user input for his/her birth-date in the same format. Then use cin.get to read the numbers, and ignore the forward slashes. After that the person's age must be determined.
My problem is, once I read each character of the date, I can't figure out how to add these chars together to make 3 integers. One for the day, one for the month and one for the year.
For the first two numbers, you can use std::getline with '/' being the character to stop at, and for the last it would of course be '\n'. You can hen use stringstreams to convert the std::strings to integral types.
You should also check out the time and date library introduced to C++11 (the latest language standard that came out in 2011): http://en.cppreference.com/w/cpp/chrono
Thank you very much for the reply, I feel like a total idiot now, so straight forward...
Here is what I have done now:
To get the day: getline(cin, sDay, '/');
To convert the day to integer: iCurrentDay = atoi(sDay.c_str());
I did this for the month and year as well. After getting all the values, I then calculate the age.
How would one go about doing this with cin.get though? Since the characters are then separate, and I can't seem to get them to append into a single integer for example an integer for day. If I say myInteger = myChar1 + myChar2, the ASCII values are added together...
#include <string>
#include <sstream>
#include <iostream>
usingnamespace std;
int main()
{
string stringNumber("100");
int intNumber;
// Attaches stringNumber to the stringstream;
stringstream ss(stringNumber);
// Writes stringNumber into integer form and stores in intNumber
ss >> intNumber;
cout << intNumber + 100 << endl;
}
EDIT:
Here is somethign personalized towards your question, feel free to rework it and make it do exactly what you want :) Hope it helps a bit.
#include <string>
#include <sstream>
#include <iostream>
usingnamespace std;
int main()
{
string date;
cout << "Enter your birthdate in MM/DD/YYYY format: ";
cin >> date;
// Holds the "/" in the date format.
char temp;
int month;
int day;
int year;
// Attaches the date to the stream
stringstream ss(date);
// Writes the date into each of its respective variables.
// The temp in there is to hold the "/" that we don't want.
ss >> month >> temp >> day >> temp >> year;
cout << "Month: " << month << endl;
cout << "Day: " << day << endl;
cout << "Year: " << year << endl;
}