using getline() and then extracting strings from user input (using C++) - c++

Hi guys I'm not really understanding how I would separate the users inputs when using getline(). For example the user inputs his birth date and from that I extract the month, date, and year from that.
eg.) for Sunday, January 2, 2010. I have
int main()
{
string inputStream;
string date, month, day, year;
string i;
string j;
getline(cin, inputStream);
//cin >> date >> month >> day >> year;
i = inputStream.substr(0, inputStream.find(","));
j = inputStream.substr(inputStream.find(","), inputStream.find(","));
date = i;
month = j;
cout << month << " " << day << " was a " << date << " in" << year << endl;
return0;
}
For i it works properly and will display sunday but for j it doesn't seem to want to work. Can someone show me where I went wrong? I'm not sure how I would extract the next value after the date.

Following modifications are done in your code to parse the day, date, month and year from the input string (as per your input format) successfully.
#include <iostream>
using namespace std;
int main()
{
string inputStream;
string date, month, day, year;
string i;
string j;
getline(cin, inputStream);
// day
day = inputStream.substr(0, inputStream.find(","));
// month
int pos1 = inputStream.find(",") + 2; // Go ahead by 2 to ignore ',' and ' ' (space)
int pos2 = inputStream.find(" ", pos1); // Find position of ' ' occurring after pos1
month = inputStream.substr(pos1, pos2-pos1); // length to copy = pos2-pos1
// date
int pos3 = inputStream.find(",", pos2); // Find position of ',' occurring after pos2
date = inputStream.substr(pos2, pos3-pos2); // length to copy = pos3-pos2
// year
year = inputStream.substr(pos3+2); // Go ahead by 2 to ignore ',' and ' ' (space)
cout << "day = " << day << endl;
cout << "date = " << date << endl;
cout << "month = " << month << endl;
cout << "year = " << year << endl;
return 0;
}
Hope this helps you.

Related

Printing a void c++

To give background on my code. I'm supposed to take the user input, find the month and day they input in the txt file and print that out which sound sooo simple to me but I just can't get my code to work. I want to take that I created and put it in the main so I can print whatever I have cout in that void code. I wanted some guidance to see where exactly I'm going wrong.
int main() {
cout << "please enter month first and then day: ";
cin >> searchMonth;
cin >> searchDay;
if (searchMonth == month && searchDay == day){
for (int i=0; i<TOTALDATA; i++){
infile >> year >> month >> day >> hour >> minute >> latitude >> longitude >> magnitude >> state;
earthquakeData oneEarthquake;
oneEarthquake.yearOfEarthquake = year;
oneEarthquake.monthOfEarthQuake = month;
oneEarthquake.dayOfEarthquake = day;
oneEarthquake.hourOfEarthquake = hour;
oneEarthquake.minOfEarthquake = minute;
oneEarthquake.yearOfEarthquake = latitude;
oneEarthquake.earthquakeLatitude = longitude;
oneEarthquake.earthquakeMagnitude = magnitude;
oneEarthquake.earthquakeState = state;
earthquakes[i] = oneEarthquake;// row i is set to oneEarthquake
earthquakeDetails (earthquakes[i]) ;
}
}
infile.close();
return 0;
}
void earthquakeDetails (earthquakeData earthquakes[TOTALDATA]){
for (int i=0; i<TOTALDATA; i++){
cout << earthquakes[i].yearOfEarthquake;
cout << earthquakes[i].monthOfEarthQuake;
cout << earthquakes[i].dayOfEarthquake;
cout << earthquakes[i].hourOfEarthquake << ":" << earthquakes[i].minOfEarthquake;
cout << earthquakes[i].earthquakeLatitude << earthquakes[i].earthquakeLongitude;
cout << earthquakes[i].earthquakeMagnitude;
cout << earthquakes[i].earthquakeState;
}
}```
Things you are doing wrong:
read from user without checking the input
read from file before opening a file (or your MRE is incomplete)
if outside of loop
if before reading from file
calling looping output function from looping search function

In C++ is there a way for me to have a function without passing an argument?

I have to write a code that outputs a formatted date when the user inputs 3 integers but also outputs a default date of 1/1/2019. I'm supposed to use a class and objects for this but i can't figure out how to get it to work without any arguments being passed from the object. Here's my current code
class Date
{
private:
int defaultDay = 1;
int defaultMonth = 1;
int defaultYear = 2019;
public:
Date()
{
int day = defaultDay;
int month = defaultMonth;
int Year = defaultYear;
}
void dateFormat(int day,int month,int year)
{
defaultDay = day;
defaultMonth = month;
defaultYear = year;
cout << day << "/" << month << "/" << year << endl;
}
}
int main()
{
Date setDate,
int day, month, year;
cin >> day;
while(day < 1 || day > 31)
{
cout << "Please enter a number between 1 and 31" << endl;
cin >> day;
}
cin >> month;
while(month < 1 || month > 12)
{
cout << "Please enter a number between 1 and 12" << endl;
cin >> month;
}
cin >> year;
setDate.dateFormat(day, month, year);
return 0;
}
I'm going to make minimal changes to your code to show you some things you can do.
class Date
{
private:
int day = 1;
int month = 1;
int year = 2019;
public:
// Default constructor with no arguments.
Date()
{
}
// Constructor with arguments.
Date(int _day, int _month, int _year)
{
day = _day;
month = _month;
year = _year;
}
//print me.
void print() const {
cout << day << "/" << month << "/" << year << endl;
}
}
Date firstDate(); // Will use defaults
Date secondDate(1, 11, 2019); // November 11, 2019
Here's what I did... First, I renamed your fields. You don't need defaultDay etc unless you have another reason for them.
Next, I gave you two constructors, one with no arguments (called the default constructor), and one with arguments. Classes can have as many constructors as you want, as long as the signatures are different.
Then I made a print method.
I hope this helps.

Subtracting an arbitrary date from the current date C++

I'm brand new to C++. In my Programming I class, I've been given the following assignment as a midterm:
-Calculate how many days you have been alive
(epoch time from 01/01/1970 stored by seconds)
-Command Line Args for Birth Year, Birth Month, Birth Day
Now, I've already figured out the function itself for actually subtracting two dates from each other, and I've figured out how to grab the current date and stick it in that function. The problem I'm having is how to get the user's entered date and send that to the function.
I've been playing with a "test" piece of code to get this to work, unfortunately when I try to compile this I just get a MOUNTAIN of errors that I don't understand at all, so I'm clearly doing something wrong.
#include <iostream>
#include <ctime>
using namespace std;
struct tm a(int year, int month, int day)
{
struct tm birth {0};
cin >> year >> endl;
cin >> month >> endl;
cin >> day >> endl;
birth.tm_year = year - 1900;
birth.tm_mon = month;
birth.tm_mday = day;
return birth;
}
int main()
{
int year, month, day;
cout << "Enter a year, month, and day: " << endl;
cin >> year >> month >> day >> endl;
tm a(year, month, day);
time_t x = mktime(&a);
time_t y = time(0);
if ( x != (time_t)(-1) && y != (time_t)(-1) )
{
double difference = difftime(y, x) / (60 * 60 * 24);
cout << ctime(&x);
cout << ctime(&y);
cout << "difference = " << difference << " days" << endl;
}
return 0;
}
I've tried googling some of these errors, and the results I'm seeing keep talking about "pointers". I have no clue what pointers are, and flipping through our textbook, it looks like something that's about three or four chapters ahead of where we are now. I tried asking my professor about this the other day, and he just sort of giggled and said something to the effect of "Well yeah, that's the point of the midterm." I don't understand if that means I'm supposed to figure out pointers on my own or if I'm not supposed to use them.
I'm trying to get a year, month, and day from arguments entered by the user at the point of execution and stick them into a struct tm so that my function at the bottom will work.
EDIT: I figured out that I am trying to use the struct like a function, which is wrong. I have made the following changes:
#include <iostream>
#include <ctime>
using namespace std;
struct tm bday(int year, int month, int day)
{
struct tm r {0};
r.tm_year = year - 1900;
r.tm_mon = month;
r.tm_mday = day;
return r;
}
int main()
{
int year, month, day;
cout << "Enter a year, month, and day: " << endl;
cin >> year >> endl;
cin >> month >> endl;
cin >> day >> endl;
struct tm a = bday(year, month, day);
time_t x = mktime(&a);
time_t y = time(0);
if ( x != (time_t)(-1) && y != (time_t)(-1) )
{
double difference = difftime(y, x) / (60 * 60 * 24);
cout << ctime(&x);
cout << ctime(&y);
cout << "difference = " << difference << " days" << endl;
}
return 0;
}
Now getting the following errors when compiling:
filename.cpp:22:17: error: no match for 'operator>>'
filename.cpp:23:18: error: no match for 'operator>>'
filename.cpp:24:16: error: no match for 'operator>>'
This is not correct:
cin >> year >> endl;
You cannot read anything into endl. You probably confused input with output where std::cout << x << std::endl; is a common pattern. However, as a sidenote, you dont need endl after each line for output either. endl not only adds a newline character, but also flushes the stream. If you just want to start a new line then use \n only.

C++ compare dates to get age

Hello I am new to C++ expecialy dates in C++.. how can I compare these numbers 29(day) 08(month) 86(year) with todays date to get age ?
Here is hwo I started my function:
std::string CodeP, day, month, year, age;
std::cout<<"Enter Permanent Code(example: SALA86082914) :\n "; //birthday first six numbers in code
std::cin>>CodeP;
year = CodeP.substr (4,2);
month = CodeP.substr (6,2);
day = CodeP.substr (8,2);
std::cout<<"day :"<<day <<'\n';
std::cout<<"month :"<<month <<'\n';
std::cout<<"year :"<<year <<'\n';
//then get today's date to compare with the numbers of birthday to get age
First subtract the years to get the difference. Now compare the months; if today's month is greater than the birth month, you're done. If not, compare the days; if today's day is greater than the birth day, you're done. Otherwise subtract one from the difference and that's the age.
Try my code below, I already did the necessary code for the comparing and the processing of two dates that you will be needing. Take note that my code's role is just to compare two dates and give the resulting age based from those dates.
Sorry but I have to leave you the job of creating a code that will give you your expected output based from a six-digit birthday input. I guess you already know that you still have to come up with your own solution for your problem, we are only here to give you an idea on how you can tackle it. We could only do so much to help and support you. Hope my post was helpful!
class age
{
private:
int day;
int month;
int year;
public:
age():day(1), month(1), year(1)
{}
void get()
{
cout<<endl;
cout<<"enter the day(dd):";
cin>>day;
cout<<"enter the month(mm):";
cin>>month;
cout<<"enter the year(yyyy):";
cin>>year;
cout<<endl;
}
void print(age a1, age a2)
{
if(a1.day>a2.day && a1.month>a2.month)
{
cout<<"your age is DD-MM-YYYY"<<endl;
cout<<"\t\t"<<a1.day-a2.day<<"-"<<a1.month-a2.month<<"-"<<a1.year-a2.year;
cout<<endl<<endl;
}
else if(a1.day<a2.day && a1.month>a2.month)
{
cout<<"your age is DD-MM-YYYY"<<endl;
cout<<"\t\t"<<(a1.day+30)-a2.day<<"-"<<(a1.month-1)-a2.month<<"-"<<a1.year-a2.year;?
cout<<endl<<endl;
}
else if(a1.day>a2.day && a1.month<a2.month)
{
cout<<"your age is DD-MM-YYYY"<<endl;
cout<<"\t\t"<<a1.day-a2.day<<"-"<<(a1.month+12)-a2.month<<"-"<<(a1.year-1)-a2.year;
cout<<endl<<endl;
}
else if(a1.day<a2.day && a1.month<a2.month)
{
cout<<"your age is DD-MM-YYYY"<<endl;
cout<<"\t\t"<<(a1.day+30)-a2.day<<"-"<<(a1.month+11)-a2.month<<"-"<<(a1.year-1)-a2.year;
cout<<endl<<endl;
}
}
};
int main()
{
age a1, a2, a3;
cout<<"\t Enter the current date.";
cout<<endl<<endl;
a1.get();
cout<<"\t enter Date of Birth.";
cout<<endl<<endl;
a2.get();
a3.print(a1,a2);
return 0;
}
this will calculate an aproximate of the age(years):
#include <ctime>
#include <iostream>
using namespace std;
int main(){
struct tm date = {0};
int day, month, year;
cout<<"Year: ";
cin>>year;
cout<<"Month: ";
cin>>month;
cout<<"Day: ";
cin>>day;
date.tm_year = year-1900;
date.tm_mon = month-1;
date.tm_mday = day;
time_t normal = mktime(&date);
time_t current;
time(&current);
long d = (difftime(current, normal) + 86400L/2) / 86400L;
cout<<"You have~: "<<d/365.0<<" years.\n";
return (0);
}
The best way to do that is using Boost.Gregorian:
Assuming
#include <boost/date_time/gregorian/gregorian.hpp>
using namespace boost::gregorian;
You would do:
date bday { from_undelimited_string(std::string("19")+a.substr(4,6)) };
date now = day_clock::local_day();
unsigned years = 0;
year_iterator y { bday };
while( *++y <= *year_iterator(now) )
++years;
--y;
std::cout << *y << "\n";
unsigned months = 0;
month_iterator m { *y };
while( *++m <= *month_iterator(now) )
++months;
--m;
std::cout << *m << "\n";
unsigned days = 0;
day_iterator d { *m };
while( *++d <= *day_iterator(now) )
++days;
--d;
std::cout << *d << "\n";
std::cout << years << " years, " << months << " months, " << days << " days\n";
I found another (simpler?) answer, using Boost.Gregorian
#include <boost/date_time/gregorian/gregorian.hpp>
using namespace boost::gregorian;
template<typename Iterator, typename Date>
struct date_count : public std::pair<unsigned, Date> {
typedef std::pair<unsigned, Date> p;
operator unsigned() { return p::first; }
operator Date() { return p::second; }
date_count(Date begin, Date end) : p(0, begin) {
Iterator b { begin };
while( *++b <= end )
++p::first;
p::second = *--b;
}
};
And you just have to use it this way:
date bday { from_undelimited_string(std::string("19")+a.substr(4,6)) };
date now = day_clock::local_day();
date_count<year_iterator, date> years { bday, now };
date_count<month_iterator, date> months { years, now };
date_count<day_iterator, date> days { months, now };
std::cout << "From " << bday << " to " << now << " there are " <<
std::setw(5) << years << " years, " <<
std::setw(3) << months << " months, " <<
std::setw(3) << days << " days\n";
If you just want the number of years, you can do:
date_count<year_iterator> years(bday, now);
and run with the number of years in the "years" variable. :D

Can I compare a char* (month) with a string (February)? If not, how can I go about doing this?

I want the program to work so that I can turn any worded month to its equivalent number.
#include <iostream>
using namespace std;
int main()
{
char month[20];
int INT_month;
cout << "Enter a month: (ex. January, February)";
cin >> month; // Let's say the input is February
if (month == "February")
INT_month = 2;
cout << "The month in its' integral form is " << INT_month << endl;
// INT_month = 2130567168 // WHY DOES IT DO THIS????
return 0;
}
One way to do it is creating a vector of month names, and using the look-up index plus one as the month number:
vector<string> months = {
"january", "february", "march", ...
};
string search = "march";
auto pos = find(months.begin(), months.end(), search);
if (pos != months.end()) {
cout << "Month number: " << distance(months.begin(), pos) + 1 << endl;
} else {
cerr << "Not found" << endl;
}
This prints 3 (demo on ideone).