I'm new to this site and to C++ and I have a question...
Instead of having three while loops, is it possible to condense this code into something smaller without using anything more advanced than structures and loops?
//_getche and loops
#include <iostream>
#include <conio.h>
usingnamespace std;
struct date
{
int day, month, year;
};
int main()
{
date date1 = {0, 0, 0};
char ch = 'a';
cout << "Enter a date (eg. 31/12/2000): ";
while ((ch = _getche()) != '/')
{
date1.day *= 10;
date1.day += (ch - 48);
}
while ((ch = _getche()) != '/')
{
date1.month *= 10;
date1.month += (ch - 48);
}
while ((ch = _getche()) != '\r')
{
date1.year *= 10;
date1.year += (ch - 48);
}
cout << endl << "The date you input was: ";
cout << date1.day << '/' << date1.month << '/' << date1.year;
_getch();
return 0;
}
All I want is to get input from the user in the form of "01/01/2008" and store each number into three separate structure members and then print the values onto the screen. I was hoping to save some lines by recycling the math inside the loops... so far this is the best I can do.
Any time you find yourself writing the same code over and over (with small variations) it is worth considering whether or not you can offload it into a separate function.
Hope this helps.
[edit]
Hmm. Except for line 38, there is no compelling reason for you to be using _getch() over the more standard cin.get() or <cstdio>'s getchar().
Finally, you can easily do what you want with cin itself:
1 2 3
char c;
cin >> date.day >> c >> date.month >> c >> date.year;
cin.ignore( 10000, '\n' );
But if you are doing homework stick to the assignment...
Thanks for the info... it's technically not an assignment, but I am using a book with exercises and I'm trying to do them with the concepts that have come up already. I've read ahead and considered a function, but they're technically in the next chapter. That's what the loops and structures restriction is all about.
However, the 3 lines of code you gave me are very interesting. I haven't seen the cin.ignore before so I'm going to experiment with that. I appreciate the help!