Is there an IDE that offers C++ <Thread> support? - c++

Thank you for taking the time to read my first query. I'm new to C++ and am honestly exhausted. I've spent more time trying to find an IDE that supports "thread" than I have learning the language. Tried DevC++ 5.5.3, Eclipse 4.3.1 and am currently trying Visual Studio Express 2013. I think my code is solid, but of course I could be wrong. More than likely wrong, perhaps. Here's a sample:
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <thread>
#include "IntervalSelection.h"
#include "Acnt.h"
using namespace std;
int main(int argc, char *argv[])
{
cout << "Hello, Mommy. To begin, what is your name?\n";
char NewMommyName[40];
cin >> NewMommyName;
std::thread t1 (Account()), (NewMommyName));
Supply * pS;
std::time_t NewPumpTime = PumpTime(pS);
struct tm * ptm = std::localtime(&NewPumpTime);
std::chrono::steady_clock::time_point TP =
std::chrono::steady_clock::from_time_t(mktime(ptm));
std::this_thread::sleep_until(TP);
std::cout << " The time is now " << std::put_time (TP, "%X")<<"\nTime to pump!";
t1.join();
//The following errors are generated:
//"no instance of function template "std::put_time" matches the argument list"
//"expression must have class type" (t1.join())
//"expected a ';' - on this line: std::thread t1 (Account()), (NewMommyName));
//"left of '.join' must have class/struct/union"
//"syntax error : ')' - on this line: std::thread t1 (Account()), (NewMommyName));
//error C2040: 'NewMommyName' : 'std::thread' differs in levels of indirection
//from 'char [40]'
There seem to be plenty of folk with a great deal more experience than me who have complaints about finding thread support. Is the error mine or some bug that I can't work around? Is there an IDE I can use that offers less of a headache in this area?
Below is the more consequential of the two header files along with errors that I'm getting when I try to build:
#ifndef ACNT_H
#define ACNT_H
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <thread>
#include "IntervalSelection.h"
using namespace std;
inline
std::string timeString(const std::chrono::steady_clock::time_point& tp)
{
std::time_t t = std::chrono::steady_clock::to_time_t(tp);
std::string ts = ctime(&t);
ts.resize(ts.size() - 1);
return ts;
}
inline
std::chrono::steady_clock::time_point MakeTime(int year, int mon, int day, int
hour, int min, int sec = 0)
{
struct std::tm t;
t.tm_sec = sec;
t.tm_min = min;
t.tm_hour = hour;
t.tm_mday = day;
t.tm_mon = mon - 1;
t.tm_year = year - 1900;
t.tm_isdst = -1;
std::time_t tt = std::mktime(&t);
if (tt == -1){ throw "Not a valid system time."; }
return std::chrono::steady_clock::from_time_t(tt);
}
class Supply
{
friend time_t PumpTime(Supply*);
public:
Supply()
{
double MilkOz = 0.0;
long long tempInterval = 0;
char* dayOrnight;
int year, mon, day, hour, min, sec = 0;
char morning[5] = "a.m.";
char evening[5] = "p.m.";
cout << "\nHow many ounces of milk do you currently have in your
supply?\n";
cout << "For greater accuracy, feel free to enter this value in decimal
form (e.g. 4.5): ";
cin >> MilkOz;
cout << "\nIdeally, how often would you like to pump?\n";
tempInterval = IntervalSelection();
std::chrono::steady_clock::time_point NOW =
std::chrono::steady_clock::now();
time_t currentTp = std::chrono::steady_clock::to_time_t(NOW);
struct tm* local;
local = localtime(&currentTp);
switch (local->tm_hour){ case 12: dayOrnight = evening; break; case 0:
local->tm_hour = (local->tm_hour) + 12; dayOrnight = morning; break; }
if (local->tm_hour > 12){ local->tm_hour = (local->tm_hour) - 12;
dayOrnight = evening;; }
else if (local->tm_hour < 12){ dayOrnight = morning; }
printf("The time is now %d: %d: %d %s", local->tm_hour, local->tm_min,
local->tm_sec, dayOrnight);
cout << "\n";
std::chrono::steady_clock::time_point tNew =
std::chrono::steady_clock::from_time_t(currentTp);
static std::chrono::steady_clock::time_point tt = tNew +
std::chrono::hours(tempInterval);
std::time_t structable, structable2 =
std::chrono::steady_clock::to_time_t(tt);
struct tm* localNew;
localNew = localtime(&structable);
switch (localNew->tm_hour){ case 12: dayOrnight = evening; break; case 0:
localNew->tm_hour = (localNew->tm_hour) + 12; dayOrnight = morning; break; }
if (localNew->tm_hour > 12){ localNew->tm_hour = (localNew->tm_hour) - 12;
dayOrnight = evening; }
else if (localNew->tm_hour < 12){ dayOrnight = morning; }
printf("Your new pump time is scheduled for %d: %d: %d %s",
localNew->tm_hour, localNew->tm_min, localNew->tm_sec, dayOrnight);
cout << "\nTo accept this time enter 'yes'. To specify a different time,
enter 'no'.\n";
char choice[4];
const char* yes = "yes";
const char* no = "no";
cin >> choice;
if (strncmp(choice, yes, 1) == 0)
{
std::string date = ctime(&structable);
date.resize(date.size() - 1);
cout << "Thank you. Your next pump time is confirmed for " << date;
std::time_t tpNewest = structable2;
}
else if (strncmp(choice, no, 1) == 0)
{
cout << "Please enter an exact date to schedule your next pump
time.\n";
cout << "Enter the current year: ";
cin >> year;
cout << "\nEnter a numerical value for the month. For example, the
number one is equivalent to the month of January: ";
cin >> mon;
cout << "\nEnter the numerical day of the month: ";
cin >> day;
cout << "\nEnter the hour: ";
cin >> hour;
cout << "\nEnter the minutes: ";
cin >> min;
static auto tpNew = MakeTime(year, mon, day, hour, min, sec);
cout << "Your next pump time is scheduled for " <<
timeString(tpNew) << endl;
std::time_t tpNewest = std::chrono::steady_clock::to_time_t(tpNew);
}
}
double entry = 0;
double getSupply(double MilkOz, double entry)
{
TotalSupply = MilkOz + entry;
return TotalSupply;
}
~Supply(){}
private:
double TotalSupply;
std::time_t tpNewest;
};
time_t PumpTime(Supply* pS)
{
return pS->tpNewest;
}
class Baby
{
public:
Baby()
{
double lbs = 0.0;
double oz = 0.0;
char pbName[40];
char pbGender[40];
cout << "\nWhat is your Baby's name?" << endl;
cin >> pbName;
strncpy(BabyName, pbName, 40);
cout << "And is " << this->BabyName << " a Boy or a Girl?\n";
cin >> pbGender;
strncpy(BabyGender, pbGender, 5);
if (strncmp(this->BabyGender, "boy", 1) == 0)
{
cout << "\nWhat is his weight in pounds and ounces?\n";
cout << "For example: My baby weighs 16 lbs and 4 oz. \n";
cout << "Pounds: ";
cin >> lbs;
cout << "\n Ounces: ";
cin >> oz;
Baby::getWeight(lbs, oz);
}
else if (strncmp(this->BabyGender, "girl", 1) == 0)
{
cout << "\nWhat is her weight in pounds and ounces?" << endl;
cout << "For example: My baby weighs 16 lbs and 4 oz. \n";
cout << "Pounds: ";
cin >> lbs;
cout << "\nOunces: ";
cin >> oz;
Baby::getWeight(lbs, oz);
}
cout << "\n" << this->BabyName << "'s current weight is " <<
this->BabyWeight << " pounds";
}
double getWeight(double pounds, double ounces)
{
ounces = ounces * 1 / 16;
BabyWeight = pounds + ounces;
return BabyWeight;
}
~Baby(){}
private:
char BabyName[40];
char BabyGender[5];
double BabyWeight;
};
class Mommy
{
public:
Mommy(char* paName)
{
strncpy(MommyName, paName, 40);
}
~Mommy(){}
private:
char MommyName[40];
Baby b;
Supply s;
};
class Account
{
public:
Account(char* paName) :m(paName)
{
strncpy(Name, paName, 40);
}
~Account(){}
private:
char Name[40];
Mommy m;
};
#endif
//ERRORS:
//expression must have class type -t1.join();
//expected a type specifier -std::thread t1 (Account()), (NewMommyName));
//left of '.join' must have class/struct/union
//syntax error : '(' -std::thread t1 (Account()), (NewMommyName));

You have extra parentheses in this line (including an unclosed one):
std::thread t1 (Account()), (NewMommyName));
It should be:
std::thread t1 (Account, (NewMommyName));
Also - your call to std::put_time is incorrect. put_time takes a const std::tm* not time_point. You would need to convert it to a std::tm in order to pass it to put_time
Without the rest of the code, it is hard to diagnose more than those couple of errors. I would suspect your issue is not compiler support.

Related

Calculations wont display in output

I'm a student in a basic programming class and I'm trying to complete this program for a class assignment. It's a simple program that calculates compounded interest by the inputs of the user. However, when writing the code, I noticed that the the result is 0 even though based on the input I would expect otherwise. Could anyone tell me why the program isn't showing results?
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}
Yes. You are not calling the futureValue function which would compute the value for you. Due to the value not being computed, it remains 0. Fix:
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
futureValue(); //Here we compute the value
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}

How do I seed the random number generator with the current time, display header and assign random birth dates to X amount of people (C++)

I'm working on an assignment where I have to create a program that:
Ask user for their name
Prompts the user for # of voters
Store user entered value
Report errors if the user enters a negative number or a character
seed the random number generator with the current time
display header
for (voterCount = 0; voterCount < numVoters; voter++)
use random number generator to:
generate bYear (restricted between 1900 and 2000)
generate bMonth
generate bDay (limit 1 and 31)
I have the first 4 down:
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
int numVoters;
char name[35]; // Variable that stores "Name" of user added max char to be 25
const int MIN_MONTH = 1;
const int MAX_MONTH = 12;
int bMonth;
cout << "Please enter your first name: ";
cin.getline(name,35); // used getline because without getline I kept getting a single char
cout << "Hello " << name << endl;
cout << "Please enter amount of voters: ";
cin >> numVoters;
while (numVoters > 0)
{
cout << "You entered: " <<numVoters << endl;
}
cout << "ERROR! ERROR! WRONG DATA TYPE PLEASE RUN THE PROGRAM
AGAIN";
return 0;
}
I don't know what to do next
I've tried to continue by using what I see online but when I do I get a never-ending loop of # of voters
#include < iostream >
#include < cstdlib >
#include < time.h >
using namespace std;
int main() {
int numVoters;
char name[35]; // Variable that stores "Name" of user added max char to be 25
const int MIN_MONTH = 1;
const int MAX_MONTH = 12;
int bMonth;
cout << "Please enter your first name: ";
cin.getline(name, 35); // used getline because without getline I kept getting a single char
cout << "Hello " << name << endl;
cout << "Please enter amount of voters: ";
cin >> numVoters;
while (numVoters > 0) {
cout << "You entered: " << numVoters << endl;
}
cout << "ERROR! ERROR! WRONG DATA TYPE PLEASE RUN THE PROGRAM AGAIN";
unsigned seed = time(0); // gets current computer time
srand(seed); // seeds the random number gen
for (numVoters = 0; numVoters < 0; numVoters++)
{
bMonth = rand() % (MAX_MONTH - MIN_MONTH + 1) + MIN_MONTH;
cout << "Random month: " << bMonth << endl;
}
return 0;
}
Help with #5-7
Algorithm.
while (numVoters > 0)
{
cout << "You entered: " <<numVoters << endl;
}
cout << "ERROR! ERROR! WRONG DATA TYPE PLEASE RUN THE PROGRAM
AGAIN";
The code above is saying, that as long as numVoters is more than 0, endlessly output the numVoters. What you need is an if else statement, as you want to say if the number of voters is above 0, output the number of voters and continue to do tasks 5,6, and 7. Otherwise, you want to output error. In pseudocode:
if (numVoters > 0) {
output numVoters
do tasks 5,6,7
}
else {
output error
return 0
}
Or you could just instead do if numVoters is equal or less than 0 output error and quit the program. Place code for task 5,6,7 after the if loop, so it executes if there is no error only:
if (numVoters =< 0) {
output error
return 0
}
//code for 5,6,7 after and outside of the if loop
Also (voterCount = 0; voterCount < numVoters; voter++), seems to me to be (int voterCount = 0; voterCount < numVoters; voterCount++).
In general, I think you misunderstand while and for loops. You should read up on them to understand where you went wrong.
As someone stated your while loop is infinite if a valid value is given
gettimeofday() information may be found here http://man7.org/linux/man-pages/man2/gettimeofday.2.html
rand_r() information can be found here https://linux.die.net/man/3/rand_r
Keep these handy, these are good references for future coursework!
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <sys/time.h>
using namespace std;
const int MAX_LENGTH = 35;
const int MAX_MONTH = 12;
const int MAX_DAY = 31;
const int MAX_YEAR = 100;
void getName(char name []);
void sayName(char name []);
int getVoters();
int main() {
int numVoters;
char name[MAX_LENGTH]; // Variable that stores "Name" of user added max char to be 25
struct timeval tv;
getName(name);
sayName(name);
numVoters = getVoters();
unsigned int seed = time(0); // gets current computer time
gettimeofday(&tv,NULL);
int day = 0;
int month = 0;
int year = 0;
int voterNumber = 1;
for (int i = numVoters;i > 0;i--)
{
seed = (unsigned int)((tv.tv_sec+tv.tv_usec)*i);
month = rand_r(&seed)%MAX_MONTH + 1;
day = rand_r(&seed)%MAX_DAY + 1;
year = rand_r(&seed)%(MAX_YEAR+1) + 1900;
cout<<"Voter #"<<voterNumber++<<" DD/MM/YYY DOB: ";
cout<<day<<"/"<<month<<"/"<<year<<endl;
}
return 0;
}
void getName(char name[])
{
cout<<"Please enter your first name: ";
cin.getline(name,35);
}
void sayName(char name [])
{
cout<<"Hello "<<name<<endl;
}
int getVoters()
{
int voters = -1;
cout<<"Please enter amount of voters: ";
cin>>voters;
if(voters < 0)
{
cout << "ERROR! ERROR! WRONG DATA TYPE PLEASE RUN THE PROGRAM AGAIN";
}
else if(voters == 0)
{
cout<<"Either you entered 0 or an invalid date type";
}
else
{
cout << "You entered: " << voters << endl;
}
return voters;
}

How can I subtract two inputted dates (Years, Months, Days) taking Leap Years into consideration

I have been trying to figure out how to accurately subtract one date from another in C++. Both will be received through user input. I thought that by creating a class, along with the use of <ctime>, I would be able to do this but I have yet to find how to do so while taking Leap years into consideration, which would be the cause for the loss of accuracy that it might have.
Here is how I was approaching the task:
#include "pch.h"
#include <iostream>
#include <ctime>
using namespace std;
class Year {
private:
struct tm date3;
struct tm date2;
struct tm date;
int FirstYear, SecondYear;
int FirstMonth, SecondMonth;
int FirstDay, SecondDay;
public:
int DateCalculus(struct tm* date, struct tm* date2);
void ResultShown();
};
int Year::DateCalculus(struct tm* date, struct tm* date2) {
struct tm date3;
date3.tm_year = date->tm_year - date2->tm_year;
date3.tm_mon = date->tm_mon - date2->tm_mon;
date3.tm_mday = date->tm_mday - date2->tm_mday;
}
void Year::ResultShown() {
cout<< date3;
}
int main() {
struct tm Date = { 0, 0, 12 };
struct tm Date2 = { 0, 0, 12 };
int Firstyear, SecondYear;
int Firstmonth, SecondMonth;
int Firstday, SecondDay;
cin >> Firstday; cout << "Day 1 " << endl;
cin >> Firstmonth; cout << "Month 1 " << endl;
cin >> Firstyear; cout << "Year 1 " << endl;
cin >> SecondDay; cout << "Day 2 " << endl;
cin >> SecondMonth; cout << "Month 2 " << endl;
cin >> SecondYear; cout << "Year 2 " << endl;
Date.tm_year = Firstyear;
Date.tm_mon = Firstmonth;
Date.tm_mday = Firstday;
Year::DateCalculus(&Date, &Date2);
cout << asctime(&Date2) << std::endl;
return 0;
}

Why is my vector dropping its data?

I'm writing a basic debt calculator to practice my C++ but one of my vectors keep dropping its values.
The structure containing the vector:
struct debt
{
std::string institution, debtType;
double creditLimit, balance, intrest, debtRatio, minMonthly;
int monthsToPayOff;
std::vector <double> monthlyBalance; //this vector is giving me trouble
};
I call a function that stores each months balance minus the monthly payment in the vector.
for (auto i : vectDebt)
{
double tempBalance = i.balance;
while (tempBalance > 0)
{
i.monthlyBalance.push_back(tempBalance); //this seems to work fine
tempBalance -= i.minMonthly;
}
if (i.monthlyBalance.size() > vectMonths.size())
vectMonths.resize(i.monthlyBalance.size());
}
Visual Studio debugger shows that the values were stored properly in above code. I then try to print the values to a .csv file but at that point the vector is already empty.
//print the payoff balances in debt.csv
for (auto i: vectDebt)
{
for (int j = 0; j != i.monthlyBalance.size(); j++)
{
fileout << i.monthlyBalance[j] << ","; //the debugger shows monthlyBalance has size = 0
}
fileout << "\n";
}
Here's my complete code, any additional comments on improving the program are also appriciated:
Debt.h
#pragma warning(disable : 4996) //diable localtime warning
#ifndef DEBT_H
#define DEBT_H
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <time.h>
#include <vector>
struct debt
{
std::string institution, debtType;
double creditLimit, balance, intrest, debtRatio, minMonthly;
int monthsToPayOff;
std::vector <double> monthlyBalance;
};
class Debt
{
private:
time_t t = time(NULL);
tm *timeinfo = localtime(&t);
const std::string months[12] = { "January","February","March","April","May","June","July",
"August","September","October","November","December" };
std::ofstream fileout;
std::vector <debt> vectDebt;
std::vector <std::string> vectMonths;
public:
Debt() { }
void addDebt(debt temp)
{
vectDebt.push_back(temp);
}
std::string returnMonth(int month)
{
std::string currentMonth = months[month - 1];
return currentMonth;
}
void calcPayoff();
void printDebt();
void printPayoff();
~Debt() { }
};
#endif //DEBT_H
Debt.cpp
#include "Debt.h"
void Debt::calcPayoff()
{
for (auto i : vectDebt)
{
double tempBalance = i.balance;
while (tempBalance > 0)
{
i.monthlyBalance.push_back(tempBalance);
tempBalance -= i.minMonthly;
}
if (i.monthlyBalance.size() > vectMonths.size())
vectMonths.resize(i.monthlyBalance.size());
}
}
void Debt::printDebt()
{
fileout.open("debt.csv");
fileout << "Institution(type),Current Balance,Intrest,Min Monthly Payment,Credit Limit\n";
for (auto i : vectDebt)
{
fileout << std::fixed << std::setprecision(2) << i.institution << "("
<< i.debtType << "),"
<< i.balance << ","
<< i.intrest << ","
<< i.minMonthly << ","
<< i.creditLimit << "\n";
}
printPayoff();
fileout.close();
}
void Debt::printPayoff()
{
int monthCounter = timeinfo->tm_mon;
fileout << "\nBalance per Month until paid off:\n";
for (int i = 0; i != vectMonths.size(); i++)
{
vectMonths.at(i) = months[monthCounter % 12];
monthCounter++;
}
for (auto i : vectMonths)
fileout << i << ",";
fileout << "\n";
//print the payoff balances in debt.csv
for (auto i: vectDebt)
{
for (int j = 0; j != i.monthlyBalance.size(); j++)
{
fileout << i.monthlyBalance[j] << ",";
}
fileout << "\n";
}
}
source file:
#include "Debt.h"
void main() {
Debt newList;
int check = 1;
std::string institution = "",
debtType = "";
double balance = 0,
intrest = 0,
creditLimit = 0,
minMonthly = 0;
std::cout << "This program will ask you to enter each of your debts institution(bank name), "
<< "debt type(loan, credit, car), current balance, interest rate, credit limit, and minimum monthly payment.\n";
while (check == 1) {
debt temp;
if (check == 1) {
std::cout << "Enter name of institution: ";
std::cin >> temp.institution;
std::cout << "Enter debt type (loan, credit, car...): ";
std::cin >> temp.debtType;
std::cout << "Enter current balance: ";
std::cin >> temp.balance;
std::cout << "Enter inrest rate for this debt: ";
std::cin >> temp.intrest;
std::cout << "Enter credit limit for this debt: ";
std::cin >> temp.creditLimit;
std::cout << "Enter the minimum monthly payment for this debt: ";
std::cin >> temp.minMonthly;
temp.debtRatio = 100*(temp.balance/temp.creditLimit);
newList.addDebt(temp);
std::cout << "Add another debt? \n"
<< "1) Yes\n"
<< "2) No\n";
std::cin >> check;
}
}
newList.calcPayoff();
newList.printDebt();
}
for (auto i : vectDebt) {
//...
}
In this loop, i will be a copy of each item in vectDebt. Any changes to i will not be reflected in the items in vectDebt. What you want is a reference to each item in vectDebt. To do that change your loop to
for (auto& i : vectDebt) {
//...
}

Calculate age in seconds - strange result

I'm new in programming and new in here.
Sorry for stupid question but i have problem with result in my "calculate your age in seconds" code. It gives me weird result like 6.17725e+10 or -6.17414e+10.
Program isn't finished yet but everything except results looks fine (i don't get any error.
Sorry again and I hope for your understanding:)
#include <iostream>
using namespace std;
void title()
{
cout << "Age Calculator" << endl << endl;
}
int byear()
{
cout << "Enter your birth year: ";
int by;
cin >> by;
return by;
}
int bmonth()
{
cout << "Enter your birth month: ";
int bm;
cin >> bm;
return bm;
}
int bday()
{
cout << "Enter your birth day: ";
int bd;
cin >> bd;
return bd;
}
int cyear()
{
int cy;
cout << "Enter current year ";
cin >> cy;
return cy;
}
int cmonth()
{
cout << "Enter current month: ";
int cm;
cin >> cm;
return cm;
}
int cday()
{
cout << "Enter current day: ";
int cd;
cin >> cd;
return cd;
}
void calculate(int by, int bm, int bd, int cy)
{
double y = 31104000;
long double cby = y * by;
long double cbm = 259200 * bm;
long double cbd = 8640 * bd;
long double ccy = 31104000 * cy;
cout << endl << cby << endl;
cout << endl << ccy << endl;
cout << endl << ccy - cby << endl;
}
int main()
{
title();
int by = byear();
int bm = bmonth();
int bd = bday();
int cy = cyear();
int cm = cmonth();
int cd = cday();
calculate(by, bm, bd, cy);
cin.get();
return 0;
}
Like Kenny Ostrom commented, the shown values may look strange due to the scientific notation used by cout. To show all digits, you can change cout's precision using cout.precision(your_precision_here). See question below.
How do I print a double value with full precision using cout?
First, the numeric format you are confused by is "scientific notation". That will be enough info to open up a world of google searches, or you can just force it not to print in scientific notation.
Second, you really want to use a time library for any calendar stuff. It will handle all kinds of calendar weirdness for you, including leap years. Fortunately we have time.h
Third, I recommend using an integer type for seconds, partly to avoid rounding errors and ugly decimals, but mainly because that's what time.h uses. Just make sure it is big enough. My compiler uses a 64 bit integer for time_t, so I used that:
#include <time.h>
#include <memory>
time_t get_age_in_seconds(int year, int month, int day)
{
struct tm birthday;
memset(&birthday, 0, sizeof(birthday));
birthday.tm_year = year - 1900; // years since 1900
birthday.tm_mon = month - 1; // months since January (0,11)
birthday.tm_mday = day; // day of the month (1,31)
time_t birthday_in_seconds = mktime(&birthday);
time_t now = time(NULL);
return now - birthday_in_seconds;
}
Don't use doubles to do the calculation. You're not going to have any fractional values since you're not doing any division.
More importantly, look into mktime(), time(), and difftime(). You should be using these to do your calculation.