Reputation: 115
All the other questions i found were with different languages and were a bit too complicated for a beginner like me.
What is wrong with my code, that i cannot get the exact number of days inbetween my two input dates?
int getDate()
{
std::cout << "Begins from: i.e 7th";
int dateStart;
std::cin >> dateStart;
std::cout << "Ends: i.e 22nd";
int dateStops;
std::cin >> dateStops;
int nrDays = dateStart;
for(nrDays; nrDays < dateStops; nrDays++)
{
}
return nrDays;
}
Is this possible using for loop?
I'm sorry for asking silly questions. I have just recently started to learn C++ and lots of things are still new to me.
Thank you for your answers! :)
p.s Also, if somebody wants to throw an idea on how to exclude weekends for example, it would be really nice. Although, my gut is telling me, that it will require a whole lotta more coding than what i have the capabilities to do yet.
Upvotes: 0
Views: 83
Reputation: 2003
You have to use a separate variable to count number of days .
try this one.
int getDate()
{
std::cout << "Begins from: i.e 7th";
int dateStart;
std::cin >> dateStart;
std::cout << "Ends: i.e 22nd";
int dateStops;
std::cin >> dateStops;
int nrDays = dateStart;
int daysCount=0;
for(nrDays; nrDays < dateStops; nrDays++)
{
daysCount++;
}
return daysCount;
}
Upvotes: 2
Reputation: 283634
The problem with your loop is that you're assuming the iteration variable is a counter. That turns out to be true in many loops, but here it isn't. Your variable nrDays
is not actually a number of days at all, but a date (it starts at dateStart
and goes to dateStops
). You really want something more like this:
int nrDays = 0;
for( int date = dateStart; date < dateStops; date++)
{
if (isWeekday(date)) nrDays++;
}
return nrDays;
Note that you can't detect weekdays from just the day of the month. You need to know what month and what year, or somehow else get the day of the week.
Upvotes: 1
Reputation: 76240
Your code shouldn't compile because of this line:
std::cin dateStart;
which should be:
std::cin >> dateStart;
A part from that, you loop is useless. What you apparently want is for nrDays
to be equal to dateStop - 1
:
int nrDays = dateStop - 1;
or more precisely:
int nrDays = std::max(dateStop - 1, dateStart);
which is: the maximum between dateStart
and dateStop - 1
.
Upvotes: 0