Formatting Date

How do I get it to say "Invalid Length" if the code is greater than 8 digits or less than 8.
#include <iostream>

int main()
{
int CurrentDate, Day, Month, Year;

cout << "Please enter a date in YYYYMMDD format: ";
cin >> CurrentDate;

Day = CurrentDate % 100;
Month = ( CurrentDate / 100 ) % 100;
Year = ( CurrentDate / 10000 );

if ( CurrentDate < 0 || Day < 0 || Month < 0 || Year < 0 )
{
cout << "Please enter positive numbers" << endl;
return 0;
}

cout << "The original YYYYMMDD date of " << CurrentDate << " has been converted to MM / DD / YY format below" <<endl;
cout << Month << "/" << Day << "/" << Year << endl;

return 0;
}
Last edited on
Hello cplusplusgod12,

Enter the number as a string. Check its length. then convert it to a number and use what you have.

Either "std::cin >>" or "std::getline()" will work.

Hope that helps,

Andy
Hello cplusplusgod12,

I put this quickly. It may not be the best, but it will give you an idea of what can be done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <limits>
#include <string>

int main()
{
	constexpr size_t LENGTH{ 8 };
	int Day{}, Month{}, Year{}, currentDate{};
	//std::string sCurrentDate{ "20190905" }; // <--- Set up for testing.
	std::string sCurrentDate;

	std::cout << "\n Please enter a date in YYYYMMDD format: ";
	std::cin >> sCurrentDate; // <--- Put a comment on this line for testing.

	if (sCurrentDate.size() < LENGTH || sCurrentDate.size() > LENGTH)
		std::cout << "\n    Error message\n" << std::endl;
	else
		currentDate = stoi(sCurrentDate);

	Day = currentDate % 100;
	Month = (currentDate / 100) % 100;
	Year = (currentDate / 10000);

	if (currentDate < 0 || Day < 0 || Month < 0 || Year < 0)
	{
		std::cout << "\n Please enter positive numbers" << std::endl;
		return 0;
	}

	std::cout << "\n The original YYYYMMDD date of " << currentDate << " has been converted to MM / DD / YYYY format below\n\n ";
	std::cout << (Month < 10 ? "0" : "") << Month << "/" << (Day < 10 ? "0" : "") << Day << "/" << Year << std::endl;

	// The next line may not be needid. If you have to press enter to see the prompt it is not needed.
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue: ";
	std::cin.get();

	return 0;
}


Hope that helps,

Andy
Topic archived. No new replies allowed.