3

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
artiebucco
  • 39
  • 1
  • 3

2 Answers2

6

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.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
4

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;
}
Community
  • 1
  • 1
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158