Reputation: 39
I have problem with an C++ exercise.
In the exercise I am supposed to make the user enter a date.
The problem is when I use cin
the console jumps one line down when I push enter, so that it becomes something like this:
Enter date please: 12
/23
/2001
instead of: 12/23/2001
Can someone please help me overcome this problem.
Upvotes: 3
Views: 1159
Reputation: 66922
Robᵩ has a good answer, but I'm going to extend it. Use a struct, and an overloaded operator, and check the slashes.
struct date {
int day;
int month;
int year;
};
std::istream& operator>>(std::istream& in, date& obj) {
char ignored1, ignored2;
in >> obj.day>> ignored1 >> obj.month>> ignored2 >> obj.year;
if (ignored1!='/' || ignored2!='/')
in.setstate(in.rdstate() | std::ios::badbit);
return in;
}
If you have code for streaming in literals, this can be simplified to:
std::istream& operator>>(std::istream& in, date& obj) {
return in >> obj.day>> '/' >> obj.month>> '/' >> obj.year;
}
Upvotes: 4
Reputation: 168616
You don't say how you use cin
to read the date. Try this:
char ignored;
int day, month, year;
std::cin >> month >> ignored >> day >> ignored >> year;
Then, when you run your program, don't push enter until you've typed in the entire date.
Upvotes: 6