How do I use getline and stringstream to parse formatted date and time input? - c++

I have only been working on c++ for about a month. I am not really understanding how it works, however I need to write a program for school. I used a void function and it seems to be working so far,but I have no idea what to do next I am lost at line 44, I am not sure how to make it work, is there a way to take a value from a certain string? If the value is in both strings how would I determine which value? Here is my assignment:
A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. People who park their cars for longer than 24 hours will pay $8.00 per day.
Write a program that calculates and prints the parking charges. The inputs to your program are the date and time when a car enters the parking garage, and the date and time when the same car leaves the parking garage. Both inputs are in the format of YY/MM/DD hh:mm
Here's the code I've written so far:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
#include <algorithm>
#include <sstream>
using namespace std;
stringstream ss;
string enter_date;
string enter_time;
string exit_date;
string exit_time;
int calculatecharge;
int num;
int i;
int year;
int month;
int ddmmyyChar;
int dayStr;
string line;
int x;
void atk()
{
getline (cin,line); // This is the line entered by the user
stringstream ss1(line); // Use stringstream to interpret that line
ss >> enter_date >> enter_time;
stringstream ss2(enter_date); // Use stringstream to interpret date
string year, month, day;
getline (ss2, year, '/');
}
int main()
{
cout << "Please enter the date and time the car is entering "<< endl
<< "the parking garage in the following format: YY/MM/DD hh:mm"<< endl;
atk();
cout << "Please enter the date and time the car is exiting "<< endl
<< "the parking garage in the following format: YY/MM/DD hh:mm"<< endl;
atk();
if (hr - hr < 3)
cout<<"Parking fee due: $2.00" << endl;

Write a program that calculates and prints the parking charges.
This is the goal of our program. Basically, this is the output.
The inputs to your program are the date and time when a car enters the
parking garage, and the date and time when the same car leaves the
parking garage. Both inputs are in the format of YY/MM/DD hh:mm
So, we want some way of translating the date format entered as a string into a time difference. You could store the time in an int, which represents the amount of minutes elapsed during the parking period (I choose minutes since this is the smallest time period inputted). The challenge here is the parsing of the string into this integer.
You could write a function like this:
int parseDate( std::string dateStr )
{
// Format: YY/MM/DD hh:mm
int year = atoi( dateStr.substr( 0, 2 ).c_str() );
int month = atoi( dateStr.substr( 3, 2 ).c_str() );
int day = atoi( dateStr.substr( 6, 2 ).c_str() );
int hour = atoi( dateStr.substr( 9, 2 ).c_str() );
int min = atoi( dateStr.substr( 12, 2 ).c_str() );
// Now calculate no. of mins and return this
int totalMins = 0;
totalMins += ( year * 365 * 24 * 60 ); // Warning: may not be accurate enough
totalMins += ( month * 30 * 24 * 60 ); // in terms of leap years and the fact
totalMins += ( day * 24 * 60 ); // that some months have 31 days
totalMins += ( hour * 60 );
totalMins += ( min );
return totalMins;
}
Careful! My function here is just an illustration, and does not take into account subtleties like leap years and varying month length. You will probably need to improve on it. The important thing is to recognise that it attempts to take a string and return the number of minutes that have elapsed since year '00. This means we simply have to subtract two integers from the two date strings to find the elapsed time:
int startTime = parseDate( startDateString );
int endTime = parseDate( endDateString );
int elapsedTime = endTime - startTime; // elapsedTime is no. of minutes parked
This is probably the hardest part of the problem, once you have this worked out, the rest should be more straightforward. I will give you a few more tips:
A parking garage charges a $2.00 minimum fee to park for up to three
hours.
Basically just a flat rate: No matter what, the output variable that describes the cost should be equal to at least 2.00.
The garage charges an additional $0.50 per hour for each hour
or part thereof in excess of three hours.
Work out the amount of hours elapsed past three hours - subtract 180 from elapsedTime. If this is greater than 0, then divide it by 60 and store the result in a float (since it is not necessarily an integer result), called, say, excessHours. Use excessHours = floor( excessHours ) + 1; to round this number up. Now multiply this by 0.5; this is the extra cost. (Try to understand why this works mathematically).
The maximum charge for any
given 24-hour period is $10.00. People who park their cars for longer
than 24 hours will pay $8.00 per day.
I will leave this up to you to work out, since this is homework after all. Hopefully I have provided enough here for you to get the gist of what needs to be done. There are many possible approaches to this problem too, this is just one, and may or may not be "the best".

First of all as both the string for the date and the string for the time are continuous(contain no spaces), you do not need to use stringstream to parse the line. You can read the date and time just like this:
cin >> enter_date >> enter_time;
cin >> exit_date >> exit_time;
Now what you need is to convert these strings to actual dates and times. As the format of both is fixed you can write something like this:
void parse_date(const string& date_string, int& y, int& m, int& d) {
y = (date_string[0] - '0')*10 + date_string[1] - '0'; // YY/../..
m = (date_string[3] - '0')*10 + date_string[4] - '0'; // ../mm/..
d = (date_string[6] - '0')*10 + date_string[7] - '0'; // ../../dd
}
Of course this code is somewhat ugly and can be written in better way but I believe this way it is easier to understand. Having this function it should be obvious how to write this one:
void parse_time(const string& time_string, int& h, int &m);
Now that you have the date and time parsed, you need to implement a method that subtracts two dates. IN fact what you care about is the number of hours that elapsed from the enter date time to the exit date time rounded up. What I suggest here is that you convert the dates to number of days from some initial moment(say 00/01/01) and then subtract the two values. Then convert both times to number of minutes since 00:00 and again subtract them. This is not language specific so I believe these tips should be enough. Again using some built-in libraries this can be done easier but I don't think this is the idea of your assignment.
After you have the number of hours rounded up all you need to do is actually to implement the rules in the statement. This will only take a few ifs and is in fact quite easy.
Hope this helps. I am purposefully not giving more detailed explanations so that there is something left for you to think about. After all this is homework and is meant to make you think how to do it.

You don't need to perform separate input reading and parsing operations. You could pass the necessary variables by reference and read the input directly into the variables using stringstream. I would use a structure to store the date and time and overload operator- with an algorithm for subtracting two date/time values. Here's how I would do it:
#include <iostream>
#include <sstream>
using namespace std;
struct DateTime {
// Variables for each part of the date and time
int year, month, day, hour, minute;
// Naive date and time subtraction algorithm
int operator-(const DateTime& rval) const {
// Total minutes for left side of operator
int lvalMinutes = 525600 * year
+ 43200 * month
+ 1440 * day
+ 60 * hour
+ minute;
// Total minutes for right side of operator
int rvalMinutes = 525600 * rval.year
+ 43200 * rval.month
+ 1440 * rval.day
+ 60 * rval.hour
+ rval.minute;
// Subtract the total minutes to determine the difference between
// the two DateTime's and return the result.
return lvalMinutes - rvalMinutes;
}
};
bool inputDateTime(DateTime& dt) {
// A string used to store user input.
string line;
// A dummy variable for handling separator characters like "/" and ":".
char dummy;
// Read the user's input.
getline(cin, line);
stringstream lineStream(line);
// Parse the input and store each value into the correct variables.
lineStream >> dt.year >> dummy >> dt.month >> dummy >> dt.day >> dummy
>> dt.hour >> dummy >> dt.minute;
// If input was invalid, print an error and return false to signal failure
// to the caller. Otherwise, return true to indicate success.
if(!lineStream) {
cerr << "You entered an invalid date/time value." << endl;
return false;
} else
return true;
}
From here, in the main() function, declare two DateTime structures, one for the entry time and one for the exit time. Then read in both DateTime's, subtract the entry time from the exit time, and use the result to generate the correct output.

Related

How do I make my program stop having build issues and make it stop using negative numbers? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My program needs to be able to calculate the monthly phone bill and there are 3 plans: Basic where 10 hours are free and it costs 9.95, Gold where 20 hours are free and it costs 14.95, and Platinum where you have unlimited hours and it costs 19.95. When my program is given hours less than the free hours it subtracts them from the initial cost, and also it has build hours.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Set up the variables.
string input;
int hours;
int basicHours;
int goldHours;
float extraBasic;
float basicCost;
float goldCost;
// Will ask and display the user their plan and hours.
cout << "Hello! Welcome to the Comms4You Telecom Company!" << endl;
cout << "Please provide your plan." << endl;
cin >> input;
cout << input << ", Ok now please provide the amount of hours you used." << endl;
cin >> hours;
//Calculate different equations
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
//This part is for displaying to the users plans and hours.(Also calculations)
if (input == "Platinum") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $19.95.";
}
else if (input == "Gold") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $" << goldCost << ".";
}
else if (input == "Basic") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $" << basicCost << ".";
}
else
return 0;
}
The problem is in these lines:
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
Think about what they are doing.
basicHours = (hours - 10);
If hours was 11, then basicHours is now 11 - 10 = 1. This is good. But if hours was 9, then basicHours is now 9 - 10 = -1. This is not what you want; if I used less than my 10 free hours, then you want basicHours to be 0.
So you can write instead:
if (hours > 10) {
basicHours = hours - 10;
}
else {
basicHours = 0;
}
or equivalently:
basicHours = (hours > 10) ? hours - 10 : 0;
goldHours = (20 - hours)
This should be the exact same thing as basicHours, except with 20 instead of 10! I will let you adapt the above code.
basicCost = (9.95 + extraBasic); and goldCost = (14.95 + goldHours);
This is wrong. 9.95 is a monetary value, say in euros. extraBasic is a time, in hours. You cannot add hours with euros! If I used 12 hours with the basic plan, what is the result of 9.95€ + 2h? I do not know, it does not make sense.
If I used 12 hours with the basic plan, then I have to pay 9.95€, and I have to pay for the extra 2h. What is the cost of the extra 2h? It is 2 times the cost of an hour; in other words, it's the extra time multiplied by the hourly rate. You should have a constant variable called hourlyRate or basicHourlyRate in your program, with that value. Then you can write:
basicCost = 9.95 + extraBasic * basicHourlyRate;
goldCost = 14.95 + goldHours * goldHourlyRate;
Coding style: separate data and code
A good rule to follow is never to put data in your code. All literal values are data. The cost of the basic and gold and platinum plans are data. The hourly rate is data. The number of "free" hours for each plan is data. Define a few variables with explicit names, initialize those variables with the data at the very beginning of the code, then write the rest of the code without ever using a literal value. There are two reasons why this is important.
The code will be easier to read with variables. Explicit names in variables make the code meaningful; if you use literal values inside the code, the people reading your code don't know what those values stand for. Why do you subtract 10 from hours? We have to think about where this 10 comes from. However, if you write basicPayingHours = hours - freeBasicHours, we understand immediately. "The people reading your code" include StackOverflow members you're showing your code to, but also your schoolmates or coworkers, your teacher or boss, and most importantly, yourself when you read your code again six months from now.
When the data changes, it will be a lot easier to update your code if data is cleanly separated from code. Imagine you are working for this phone company. Next year, they update their plans and the basic plan is now 9.99 per month instead of 9.95. If this value is stored at the beginning of your code in a line basicPlanInitialCost = 9.95;, it is very easy to update it. However if there are multiple occurrences of 9.95 in your code, you will have to track them and change them all manually - this process is very prone to errors for two reasons: you might accidentally change the cost of something else that also costs 9.95; you might forget to update values that are dependent on the monthly price of the basic cost (like the yearly price of the basic cost, which is 12 * 9.95 = 119.40).

Using month and date together in C++

I was trying to make a program that calculated the fee of a membership at a swimming pool. The user would enter a date (the last time a member renewed the membership), and the program would calculate if their membership was overdue or not, using the current date.
The membership is meant to be overdue a week (or another arbitrary time period) before the start of the month they joined in a year's time. For example, if I joined in February 2016, I would have to pay on January 24 2017 or before to make sure the membership is overdue. As soon as it gets to January 25, a month fee should be charged ($15) and as soon as it reaches February 25, two months fee should be charged etc.
However, I do not know how to charge for subsequent months after the first one. For example, paying on February 3 should result in one month overdue but paying on February 26 should be two months but I do not know how to do this.
How can I fix my function because it doesn't seem to work?
E.g. I entered November 15 2016 and it should return 15 since the membership was due on October 24 2017 but it returns 0.
int membershipFine(int joinDay, int joinMonth, int joinYear, int currentDay, int currentMonth, int currentYear)
{
int dueDay[12] = {25, 22, 25, 24, 25, 24, 25, 25, 24, 25, 24, 25}; // the week before the end of each month in days
int correspondingMonth = joinMonth - 2; // finds the element position that corresponds
if (correspondingMonth == -1) // if they joined in january, the array will go to december
{
correspondingMonth = 11;
}
int differenceInMonths = currentMonth - joinMonth + 12 * (currentYear - joinYear);
if (differenceInMonths < 11)
{
return 0;
}
else if ((differenceInMonths == 11) && (joinDay < dueDay[correspondingMonth]))
{
return 0;
}
else if (differenceInMonths == 11)
{
return 15;
}
if (differenceInMonths > 11 && joinDay < dueDay[correspondingMonth]) // not sure about this if and else statement
{
return (differenceInMonths - 11) * 15;
}
else return (differenceInMonths - 10) * 15;
}
The best way to deal with dates and times is to use a library that raises the level of abstraction about integers, to dates and times. Howard Hinnant's free, open-source, header-only library is such a tool.
It has a {year, month, day} class called date::year_month_day that lends itself to year and month arithmetic. One could use this to change the API of membershipFine from taking 6 type-unsafe parameters to just two type-safe parameters:
int
membershipFine(date::year_month_day joinDate, date::year_month_day currentDate);
Your description of the due date appears to say that it is independent of the day of the month of the join date, and that it is 1 year, less 1 week from the first of the month of the join date. If this is true, this can be easily computed like this:
using namespace date;
year_month_day dueDate{
local_days{(joinDate.year()/joinDate.month() + years{1})/1} - weeks{1}};
The expression joinDate.year()/joinDate.month() creates a year_month object, which is just a year and month, neglecting the day-of-the-month from joinDate. I add 1 year to that year_month, which results in another year_month, exactly 1 year later.
To that sum, /1 is appended. This creates a year_month_day corresponding to the first day of the month of the aforementioned year_month.
Now even though year_month_day is great for year and month oriented arithmetic, it is not so great for day and week-oriented arithmetic. The best data structure for that is a {count-of-days} from some epoch. This library has such a data structure called local_days. So I convert to that, subtract 1 week, and then convert back to year_month_day.
All of this (to compute the due date) happens in the lines of code above.
Now I need to compute the fine based on the relationship between currentDate and dueDate. The fine is $0 if currentDate < dueDate, and otherwise is a function of the number of whole months (plus 1) currentDate is beyond dueDate (as I understand your problem statement):
int fine = 0;
if (currentDate >= dueDate)
{
auto differenceInMonths = currentDate.year()/currentDate.month() -
dueDate.year()/dueDate.month();
if (currentDate.day() >= dueDate.day())
++differenceInMonths;
fine = differenceInMonths.count() * 15;
}
The difference in months, neglecting the day-of-the-month, can be computed by converting to year_month objects and subtracting. Now if currentDate.day() < dueDate.day(), this is the correct answer. For example if the difference in months is 1, but the day of the month in currentDate has not yet exceeded the day of the month in dueDate, then we don't want to charge for a second month, else we do. If we do, differenceInMonths is incremented.
Then the fine is simply the differenceInMonths, converted from months to integral, times 15.
<aside> If there are any <chrono> fans out there, the type of differenceInMonths is actually a std::chrono::duration with a period that is exactly the average month. Thus the .count() member function to access the underlying integral value.
I've added some print statements to the above code, and below I show the whole thing put together plus a driver with a few examples:
#include "date/date.h"
#include <iostream>
int
membershipFine(date::year_month_day joinDate, date::year_month_day currentDate)
{
using namespace date;
year_month_day dueDate{
local_days{(joinDate.year()/joinDate.month() + years{1})/1} - weeks{1}};
int fine = 0;
if (currentDate >= dueDate)
{
auto differenceInMonths = currentDate.year()/currentDate.month() -
dueDate.year()/dueDate.month();
if (currentDate.day() >= dueDate.day())
++differenceInMonths;
fine = differenceInMonths.count() * 15;
}
std::cout << "join Date is " << joinDate << '\n';
std::cout << "due Date is " << dueDate << '\n';
std::cout << "current Date is " << currentDate << '\n';
std::cout << "fine is $" << fine << '\n';
return fine;
}
int
main()
{
using namespace date::literals;
std::cout << membershipFine(feb/29/2016, jan/24/2017) << '\n';
std::cout << membershipFine(feb/29/2016, jan/25/2017) << '\n';
std::cout << membershipFine(feb/29/2016, feb/24/2017) << '\n';
std::cout << membershipFine(feb/29/2016, feb/25/2017) << '\n';
}
This outputs:
join Date is 2016-02-29
due Date is 2017-01-25
current Date is 2017-01-24
fine is $0
0
join Date is 2016-02-29
due Date is 2017-01-25
current Date is 2017-01-25
fine is $15
15
join Date is 2016-02-29
due Date is 2017-01-25
current Date is 2017-02-24
fine is $15
15
join Date is 2016-02-29
due Date is 2017-01-25
current Date is 2017-02-25
fine is $30
30
In summary, the use of a library such as this frees you from having to think in terms of ints so you can concentrate on the logic you have to implement in terms of dates and calendars. The result is compact and readable code that is far more likely to be correct.
Update
In the comments below the OP asks about how to parse a date from cin and how to get the current date. There are several options.
Here is how I recommend asking for a date:
date::year_month_day join;
while (true)
{
std::cout << "Enter join date as yyyy-mm-dd: ";
std::cin >> date::parse("%F", join);
if (!std::cin.fail())
break;
std::cin.clear();
std::string garbage;
std::getline(std::cin, garbage);
std::cout << "Please try again.\n";
}
If you prefer to ask for some other format, here is the complete list of parsing flags available for use.
And the OP asks how to get the current date. There are multiple answers. If you are content with the current date in UTC, that is the simplest:
using namespace std::chrono;
using namespace date;
year_month_day today = floor<days>(system_clock::now());
If you want the current date in your local time zone, you need to use "date/tz.h" (requires some installation) and this syntax:
year_month_day today{floor<days>(make_zoned(current_zone(),
system_clock::now()).get_local_time())};
If you want the current date in some time zone other than your current local time zone, that can be done with:
year_month_day today{floor<days>(make_zoned("America/Los_Angeles",
system_clock::now()).get_local_time())};
No matter how you parse your join and today, they can be used like this:
std::cout << membershipFine(join, today) << '\n';

How to improve my code about the growing of a bacterial colony (C++) [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I'm coding a program to calculate the growth of a bacterial colony until certain point.
Given a "X", that will represent the initial number of bacteria. And given a "Y", that will represent the number limit desired of bacteria in the bacterial colony. Return the number of days and hours that the bacterial colony needs for reaching the limit.
The bacterial colony doubles each hour.
Example.1:
Input: 1, 8
Output: 0, 3
Example.2:
Input: 1000 , 1024000
Output:0, 10
Example.3:
Input: 123, 3453546624536
Output: 1, 10
If the hour calculated returns a fractional number, it must be rounded down.
So far I have written this code:
#include <iostream>
using namespace std;
int main(){
long int binitial, blimit, day, counter=0;
float hour;
cin >> binitial;
cin >> blimit;
while(binitial <= blimit){
binitial = binitial * 2;
counter++;
}
day = counter / 24;
cout << day << " ";
hour = (counter % 24) - 0.5;
cout << (int)hour;
return 0;
}
You can remove the loop by observing that the number of hours is Log2(Y/X). To calculate Log2(A) using the standard functions, calculate log(A)/log(2).
You may need to address precision issues when going from doubles to ints, because the calculations will be approximate. The final expression for the hours may look like this:
int hours = (log(Y/X) / log(2)) + 1E-8; // Add a small delta
Going from hours to days/hours is very simple, too:
cout << hours/24 << " " << hours % 24 << endl;
You can use a long int for hour if you do the following:
hour = counter - (day*24); // The total number of hours minus the number of hours that are in each day.
I don't have a compiler in front of me but you can probably also do something like this:
hour = counter % 24; // this will return the remainder when counter is divided by 24.
If blimit is always a multiple of binitial, the solution is simple:
counter%24 will be always an integer, so you don't have to round it.
In case of day days and hour hours, you only have to do is:
hour = counter%24
A note on the method of calculation: you don't need to iterate if you're only doubling each time. You're just looking for a value of n such that 2n gives the right result.
So, note that ngenerations = log2 blimit - log2 binitial
Once you have the number of generations (as a floating-point number) you can just truncate that to an integer number of hours.

am i on the right track? Cashier Program C++

I'm new to C++ and was wondering if i was on the right track? I'm kind of confused about this but was hoping for possibly some helpful hints on things i am missing/ have wrong....i know its not completely finished i still need to do the breakdown of the dollars,quarters....etc
Question: A cash register uses an automated coin machine to help make change. We assume that a clerk is handed money to pay for purchases. For change, the clerk returns to the customer any paper money and directs the coin machine to distribute any changes less then $1. In this exercise, you are to simulate the action of the clerk and the machine.
At the cash register, we need access to the purchase price and the payment. The change, which is the difference between the payment and the purchase prices, is a real number. The whole part represents the change in dollars and the fractional part is the change in cents that is returned in quarters, dimes, nickels, and pennies. For instance, with a payment of $10 to cover purchases of $3.08, the required change is $6.92. The clerk hand out $6 and the coin machine distributes 3 quarters, 1 dime, 1 nickel, and 2 pennies for the 92 cents.
92 = 3(25) + 1(10) + 1(5) + 2
Use real-number objects that identify the purchase price (price), the amount of payment (payment), and the change (change). The main program computes the amount of change (coinChange) and partitions it into dollars (dollars), quarters (quarters), dimes (dimes), nickels (nickels), and pennies (pennies).
You must declare constants for quarters (quarters), dimes (dimes), nickels (nickels), and pennies (pennies). You must use compound operators in the calculations. You must use setreal(w,p) and setw(n) for the output.
What I have done so far:
// Me
// A BRIEF PROGRAM DESCRIPTION FOR CHAPTER 2, HOMEWORK 4
// COMMENT THE PREPROCESSOR
#include <iostream.h>
// COMMENT THE PREPROCESSOR STATEMENT
#include "textlib.h"
int main( )
{
// COMMENT THE CONSTANTS
const int QUARTER_AMOUNT = 25;
const int DIME_AMOUNT = 10;
// COMMENT THE OBJECTS
double price;
double payment;
double change;
int numofDollars;
int numofQuarters;
int numofDimes;
int numofNickles;
int numofPennies;
int coinChange;
cout << "Enter the purchase total: ";
cin >> price;
cout << "Enter the payment: $";
cin >> payment;
// COMMENT THE CALCULATION
change = payment - price;
numofDollars = int(change);
coinChange = (int((change / numofDollars) * 100));
numofQuarters = coinChange / 25;
coinChange = coinChange / (numofQuarters * 25);
numofDimes = coinChange / 10;
numofNickles = coinChange / 5;
numofPennies = coinChange / 1;
// OUTPUT THE INFORMATION
return 0;
}
Yes, you are on the right track. Your general structure is sound. These sorts of homework assignments almost always have a structure like this:
int main () {
// read in the data
...
// Do the math
...
// Write out the data
...
}
You do have some math errors. Try stepping through the code with a pencil and paper, pretending that you are the computer. Also, try stepping through the code with your debugger, examining the variables after each line. Compare what actually happened to what you expected.

C++ reverse number with digit adding

Hi to all thank all in advance to those who tried to answer or answer and part of this question.
Calculate the sum of the digits of the year.
Calculate the absolute value of the difference between the year and the ’reverse’ of the year.
Calculate the number of even factors of the day.
Calculate the greatest common divisor of the day, month and year.
Calculate the number of steps required to solve the Collatz problem for
the month
These are my tasks that I need to fulfill, as Engineering student this how far I went in this. In the following codes I expect something like this
19
90
0
1
0
T M B B
The answer that I get is
Please enter your birthdate (dd mm yyyy): 12 11 1981
19
8468304
Press any key to continue . . .
8468304
How to get it right I know that my equation is right or(formula, method). However this is what I know.
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
cout << "Please enter your birthdate (dd mm yyyy): ";
int day, month, year, count,rev;
int sum = 0;
cin >> day>> month >>year;
while (year!=0)
{
int count = year%10;
sum +=count;
year /= 10;
}
while(year>0)
{
rev = year%10;
year=year/10;
}
cout<<sum<<endl;
cout << rev;
system ("pause");
return 0;
}//end main
Please help!
After your first loop, while (year != 0), you don't reset the value of year, so it remains at zero and the second loop doesn't execute at all.
You need to save the value of year and use it when you start the second loop.
Just a note on organisation: I'd suggest to write a subroutine/function for every task, like
int digit_sum(int year) {
/* ... */
return sum;
}
int reverse_difference(int year) {
/* ... */
return diff;
}
and so on. This way you'll also prevent errors like modifying the year variable during the first calculation without saving the original value (which you did, as David Winant already pointed out).