Using void and value-returning functions

closed account (SwAfjE8b)
Hey everyone! So I'm having difficulty turning the int into string and I was wondering if anyone could help me and just generally look over the program and see if I've done it correctly, Thank you in advance!

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cmath>

using namespace std;
void displayInvalidMonth();
void displayInvalidDay();

int main ()
{
ifstream inFile;
int month, day, year;
string events;

inFile.open("dates.txt");
if (!inFile)
{
cout << "File Error" << endl;
return 1;
}
cout << fixed << setprecision(2) << showpoint;
while (!(inFile.eof()))
{
inFile >> month >> day >> year;
getline(inFile,events,'\n');
if (month < 1 || month > 12)
displayInvalidMonth();
else if (day < 1 || day > 31)
displayInvalidDay();
else if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30)
displayInvalidDay();
else if (month == 2 && day > 28 && year %4 != 0)
displayInvalidDay();
else if (month == 2 && day > 29 && year %4 != 0)
displayInvalidDay();
else
cout << month << day << year << events << endl;
}

inFile.close();

system ("PAUSE");
return 0;
}
void displayInvalidMonth()
{
cout << "Error: Invalid Month" << endl;
}
void displayInvalidDay()
{
cout << "Error: Invalid Day" << endl;
}
closed account (SwAfjE8b)
I forgot to put that the file it is pulling from has this in it:

4 1 2014 April Fools!
7 4 1776 Declaration of Independence signed
13 13 2013 The most unlucky day ever
2 29 2014 Why can't this year be a leap year?

and its suppose to output:

April 1st 2014: April Fools!
July 4th 1776: Declaration of Independence signed
Error: Invalid month!
Error: Invalid day!
It's a little late for me, so this might sound a little confusing, but for the 2nd month and the 29th day, I believe the syntax is actually year%4 == 0, that looks to be the only problematic code, to turn your strings into code, you would need to write a switch statement for each variable, or use if/else, dependent on your coding style.

string returning function:
1
2
3
4
5
6
//Here we can see that I chose to use the same variable name, as the original month is in a different scope.
std::string monthRet(int month)
switch(month):
     case 1:
          return "January";
// Please note that one does not need to use a break statement ONLY in this situation, since we are returning a value 

The code to print that statement:
 
std::cout << monthRet(month)


I'll try to check back tommorow to see if you have any questions.
Last edited on
Your code works fine for me, just format some spaces between day/month/year on cout. If you must convert them I think you can use std::to_string().
Hi,

Just wanted to mention that leap years are every 4 years, but not every 100, but are every 400.

Better to test for leap year once, not twice.

Hope all goes well. :+)
Topic archived. No new replies allowed.