RayKnight wrote:
I mean, how do you split up the numbers if you put 'em together? I thought
of 'pairing' the numbers up together. So it checks if it is above 31 and
stuff after it check the month. And so on and so fore.
It all depends on how you represent the concept of 'date'.
There are vsrious choices.
You could eg. do:
* hold day, month, year in seperate int variables:
int day, month, year;
cout << "Enter date as DD MM YYYY ";
cin >> day >> month >> year;
now you have 3 int variables, holding the day, the month and the
year.
Checking that should now be straightforward. Eg. month
if( month < 1 || month > 12 )
cout << "Invalid date, month is not in the range 1 .. 12\n"
Here you rely on the user of your program to input 3 distinct numbers
* hold the day, month, year in seperate variables but read just 1 integer
int day, month, year;
int TotalDate;
cout << "Enter date as DDMMYYYY ";
cin >> TotalDate;
The user will input a number, eg. 05092005
You now will have to split this number into pieces. For this / and %
are usefull operations.
Year = TotalDate % 10000;
TotalDate /= 10000 // 5092005 / 10000 -> 509
Month = TotalDate % 100
TotalDate /= 100 // 509 / 100 -> 5
Day = TotalDate;
Now you can proceed as in the first case in doing your checks.
* Well. Relying on the user to input numbers can work or may not work. It
all depends on the user. If he plays the game safe and inputs the numbers
as you want them, fine. If not: There isn't much you can do about it, then
to recover from that error, put up an error message and continue. But that
recovering can become a hard job.
Most of the time it is far simpler, to let the user enter into a string.
You still want the user to enter in a specific format. But the difference
is: The standard input routines for numbers will cease to work if the user
enters something strange, while the standard input functions for strings
simply copy everything the user typed to the string variable. Your program
now has a chance to inspect what the user actually typed, *before* you try
to convert everything to numbers. If your program decides that the user
didn't enter 3 numbers (or 1 number) then the program can output a gracefull
error message and repeat the input without the need to worry about the standard
input functions.
Once you have a valid string, convert it into 3 (or 1) number and proceed as in
one of the first 2 cases.
* You could encapsulate all of this into a class of its own
* and so on. From now on the possibilities are endless. But it all boils down to
* You are the programmer
* You decide on how you want to store a 'date'
* You decide on how you want to input a 'date' from the user
* Dont' be frightened by implementing one scheme, figuring out that it is not
the best scheme since sliced bread, throw it away and implement another scheme.
* Implementing something and throwing it away actually *is* a form of learning.
--
Karl Heinz Buchegger
kb******@gascad.at