Hello! I am stuck on how to write a code. I have search my textbooks, googled, stared at it, all I understand is somewhere there needs to be an "if" function.
Here is the problem:
Write a program that prints the day number of the year, given the date in the form month-day-year. For example, if the input is 1-1-2006, the day number is 1; if the input is 12-25-2006, the day number is 359. The program should check for a leap year. A year is a leap year if it is divisible by 4, but not divisible by 100.
So far this is all I have:
#include <iostream>
using namespace std;
int main() {
char date;
cout << "Please enter a date (mm-dd-yyyy)." << endl;
cin >> date;
return 0;
}
Obviously my "date" is not actually set to anything but that was part of my problem. I wasn't sure how to set "date" as a multi input function. If that makes sense.
The way you have started your program, you'll never be able to input the date. A char holds 1 character only. It's best to use a string and parse it out, assigning your variables to month day and year, or, if you're allowed, use separate integer variables, like month, day and year.
#include <iostream>
int main()
{
int year, month, day;
char c;
std::cout << "Please enter a date (mm-dd-yyyy): "; // instruct the user
std::cin >> month >> c >> day >> c >> year; // get each integer, skipping the '-' between them
std::cin.ignore( std::numeric_limits <std::streamsize> ::max(), '\n' ); // get and toss the newline
std::cout
<< "Good job! You entered:\n"
<< "year = " << year << "\n"
<< "month = " << month << "\n"
<< "day = " << day << "\n";
}
Getting input with C++ is one of the more tedious and difficult things to get right, but introductory courses tend to ignore that. All the important stuff is on lines 9 (getting the integers) and 10 (getting rid of that as-yet unread newline).
It assumes the user input exactly as instructed. If the user inputs bad data, it could go wrong. Making input bulletproof is harder than people like to admit, but you shouldn’t feel too obligated to learn anything too deep about it yet.
Making input bulletproof is harder than people like to admit
Later, GUIs gloss over this as the data entry boxes they provide have some validation options (or the windows ones do, at least) you can use or they can be tied to a specific type (like int) that handles junk for you. It is thankfully rare to need to fully deal with this at the command line these days and when you do, you can use a library. I normally don't say this much but glossing over this in school is probably a wise decision.
@ everyone else:
Well for some reason they decided to cover it in a Programming I classes so *shrug*
My instructor sent me a pseudo code as a guide so hopefully that will help.