I am trying to just write something that takes a month and date and prints it back out. I have written the following code:
int main(void){
char month[] = {};
int day;
printf("Please enter the month and day of you date. i.e January 01\n\n");
scanf("%s,%d", month, &day);
printf("Month is %s and the day is %d\n", month, day);
return 0;
}
When I input a date like December 22, I get the following print out: Month is December and date is 1. The day value is stuck printing as 1. Why isn't my day integer updating and is instead just staying stuck at 1?
This declaration
char month[] = {};
is invalid in C and C++.
At least you should write for example
char month[10];
In the prompt the format of the input date is shown without a comma
printf("Please enter the month and day of you date. i.e January 01\n\n");
But in the call of scanf
scanf("%s,%d", month, &day);
there is present a comma.
The program can look for example the following way
#include <stdio.h>
int main( void )
{
char month[10];
unsigned int day;
printf( "Please enter the month and day of you date. i.e January 01\n\n" );
if (scanf( "%9s %u", month, &day ) == 2)
{
printf( "Month is %s and the day is %02u\n", month, day );
}
}
The program output might look like
Please enter the month and day of you date. i.e January 01
December 22
Month is December and the day is 22
If you want to include a comma in the input string then the program can look the following way
#included <stdio.h>
int main( void )
{
char month[10];
unsigned int day;
printf( "Please enter the month and day of you date. i.e January, 01\n\n" );
if (scanf( "%9[^,], %u", month, &day ) == 2)
{
printf( "Month is %s and the day is %02u\n", month, day );
}
}
The program output might look like
Please enter the month and day of you date. i.e January, 01
January, 01
Month is January and the day is 01
Another approach is to use function fgets instead of scanf as for example
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
char date[14];
printf( "Please enter the month and day of you date. i.e January, 01\n\n" );
int success = fgets( date, sizeof( date ), stdin ) != NULL;
if (success)
{
const char *p = strchr( date, ',' );
if (success = p != NULL)
{
char *endptr;
unsigned int day = strtoul( p + 1, &endptr, 10 );
if ( success = endptr != p + 1 )
{
printf( "Month is %.*s and the day is %02u\n",
( int )( p - date ), date, day );
}
}
}
}
The program output might look like
Please enter the month and day of you date. i.e January, 01
January, 01
Month is January and the day is 01
Related
How should the sscanf argument look like if I want the output of the print statement to be: Saturday March 25 1989
In other words I want the date to contain both Saturday AND March. I tried different sscanf format options but the print statement usually comes out gibberish.
int day, year;
char date[50], dtm[100];
strcpy( dtm, "Saturday March 25 1989" );
sscanf( dtm, "%s %d %d", date, &day, &year );
printf("%s %d %d\n", date, day, year );
in sscanf %s will get only Saturday because of the space then %d will try to extract an int from March and of course cannot
but you can do :
sscanf( dtm, "%[^0-9] %d %d", date, &day, &year );
or better
sscanf( dtm, "%49[^0-9] %d %d", date, &day, &year );
to not take the risk to write out of date (49 rather than 50 to let the space for the ending null character).
So
#include <stdio.h>
#include <string.h>
int main()
{
int day, year;
char date[50], dtm[100];
strcpy( dtm, "Saturday March 25 1989" );
if (sscanf( dtm, "%49[^0-9]%d%d", date, &day, &year ) == 3) /* remove useless spaces in format */
printf("'%s' %d %d\n", date, day, year ); /* use '%s' to show all from date */
return 0;
}
Compilation and execution:
pi#raspberrypi:/tmp $ gcc -Wall c.c
pi#raspberrypi:/tmp $ ./a.out
'Saturday March ' 25 1989
pi#raspberrypi:/tmp $
as you can see the date memorizes the separating space after the date up to the day number, it is not possible to avoid that in your case because the length of the date is variable, but you can bypass the possible spaces before using sscanf( dtm, " %[^0-9]%d%d", date, &day, &year ); :
#include <stdio.h>
#include <string.h>
int main()
{
int day, year;
char date[50], dtm[100];
strcpy( dtm, " Saturday March 25 1989" );
if (sscanf( dtm, " %49[^0-9]%d%d", date, &day, &year ) == 3)
printf("'%s' %d %d\n", date, day, year );
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -Wall c.c
pi#raspberrypi:/tmp $ ./a.out
'Saturday March ' 25 1989
pi#raspberrypi:/tmp $
Out of that dtm is useless and you can do directly :
if (sscanf(" Saturday March 25 1989",
" %49[^0-9]%d%d", date, &day, &year ) == 3)
I want to find the date,month and year through a given set of numbers using the array and pointers.I am writing the program to learn C.
Below is the output:
Enter the number : 22102013
Today is the day is 22,month is 10 and the year is 2013.
And i have wrote the following code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char date [11];
char days []="DD";
char month[]="MM";
char year []="YYYY";
printf("Enter the year that you want \n");
scanf ("%d",&date[11]);
char *my_pointer = date;
days[0] = *(my_pointer);
days[1] = *(my_pointer+1);
month[0]=*(my_pointer+2);
month[1]=*(my_pointer+3);
year [0]=*(my_pointer+4);
year [1]=*(my_pointer+5);
year [2]=*(my_pointer+6);
year [3]=*(my_pointer+7);
printf("Today the day is %s,the month is %s and the year is %s",days,month,year);
return 0;
}
Also i had not initialized the array size but it kept raising error for declaration of the array.
Your scanf should have been like this scanf ("%s",date);
#include <stdio.h>
#include <stdlib.h>
int main()
{
char date [11];
char days []="DD";
char month[]="MM";
char year []="YYYY";
printf("Enter the year that you want \n");
scanf ("%s",date);
char *my_pointer = date;
days[0] = *(my_pointer);
days[1] = *(my_pointer+1);
month[0]=*(my_pointer+2);
month[1]=*(my_pointer+3);
year [0]=*(my_pointer+4);
year [1]=*(my_pointer+5);
year [2]=*(my_pointer+6);
year [3]=*(my_pointer+7);
printf("Today the day is %s,the month is %s and the year is %s",days,month,year);
return 0;
}
You probably want this:
#include <stdio.h>
int main()
{
char date[11];
char days[] = "DD";
char month[] = "MM";
char year[] = "YYYY";
printf("Enter the year that you want \n");
scanf("%10s", date); // limit input to 10 chars to prevent buffer overflow
days[0] = date[0];
days[1] = date[1];
month[0] = date[2];
month[1] = date[3];
year[0] = date[4];
year[1] = date[5];
year[2] = date[6];
year[3] = date[7];
printf("Today the day is %s, the month is %s and the year is %s", days, month, year);
return 0;
}
or even simpler:
#include <stdio.h>
#include <string.h>
int main()
{
char date[11];
char days[] = "DD";
char month[] = "MM";
char year[] = "YYYY";
printf("Enter the year that you want \n");
scanf("%10s", date);
memcpy(days, date + 0, 2);
memcpy(month, date + 2, 2);
memcpy(year, date + 4, 4);
printf("Today the day is %s, the month is %s and the year is %s", days, month, year);
return 0;
}
Example:
Enter the year that you want
01022019
Today the day is 01, the month is 02 and the year is 2019
But be aware that this is very incovenient, because you don't check at all if the input is plausible, try to enter abcdefg instead of 01022019 and see what happens.
When I enter the date 08/01/2015 the program prints 00/00/00 instead of 08/01/2015. What seems to be the problem?
#include <stdio.h>
int main ()
{
int month = 0;
int day = 0;
int year = 0;
printf("Enter today's date (mm/dd/yyyy): ");
scanf("%i/%i/%i", &month, &day, &year);
printf("%.2i/%.2i/%.2i", month, day, year);
return 0;
}
I amended your original program to deal with several issues. But the main one was to use the correct format specifier %d in scanf(). Using %i will interpret an input as octal if it has a leading 0 - very likely when typing a date, especially as you encourage that with the output format. Months 01 to 07 did not fail because the octal input works correctly - but 08 and 09 do not, as 8 and 9 do not exist in octal number representation.
I also checked the return value from scanf() to ensure the integer date fields were correctly entered. If you had done that, you would have seen there was something wrong there.
Other things I changed are:
Checked the date you entered to be valid to avoid the GIGO syndrome.
Avoided writing to the array of days per month as commented earlier.
Restricted the year to the Gregorian calendar, as some days were missing.
Separated form from functionality. For example, your leapYear() function checked for a leap year and also tested (inadequately) - and reported errors in the date entered.
Moved the global date variables to be local vars, which are passed as function arguments.
#include <stdio.h>
struct date {
int month;
int day;
int year;
};
int daysPerMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int leapyear(int year) {
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
int validdate(struct date now) {
int daysmon;
if (now.year <= 1582) // pre-Gregorian
return 0;
if (now.month < 1 || now.month > 12)
return 0;
daysmon = daysPerMonth[now.month-1];
if (leapyear(now.year) && now.month == 2)
daysmon++;
if (now.day < 1 || now.day > daysmon)
return 0;
return 1;
}
struct date bumpdate(struct date now) {
int daysmon = daysPerMonth[now.month-1];
if (leapyear(now.year) && now.month == 2)
daysmon++;
if (++now.day > daysmon) {
now.day = 1;
if (++now.month > 12) {
now.month = 1;
now.year++;
}
}
return now;
}
int main (void) {
struct date today, tomorrow;
printf("Enter today's date (mm/dd/yyyy): ");
if (3 != scanf("%d %*[/-] %d %*[/-] %d", &today.month, &today.day, &today.year)) {
printf ("Need the proper date format\n");
return 1;
}
if (!validdate(today)) {
printf ("Invalid date\n");
return 1;
}
tomorrow = bumpdate(today);
printf("Tomorrow's date is %02d/%02d/%04d", tomorrow.month, tomorrow.day, tomorrow.year);
return 0;
}
I have a perfectly working code that is able to tell me what day of the week it is when i input a certain date, however i am stuck as to how to take in the inputs. I have to be able to take in both of these inputs in the forms:
mm/dd/yyyy~~~~~~~~~~~~~~~Example: 03/04/2014
or
Month dd, yyyy~~~~~~~~~~~~Example: March 04, 2014
I am having trouble as to how i should make my program be able to take in both these different kinds of inputs and spit out the correct weekday no matter which input is used.
#include <stdio.h>
int main(){
int inputyear, daynumb, days_passed_since_anchor, inputmonth, days_in_month,totdays_for_7,rmd_for_7;
days_in_month=days_passed_in_months(inputmonth, inputyear);
//call function to get days in all the previous months in the current year, if we are in march then there were 59 days before this month if its a non leap year.
days_passed_since_anchor = (inputyear-1905) * (365.25);
daynumb = days_in_month + inputday;
totdays_for_7 = days_passed_since_anchor + daynumb;
rmd_for_7=totdays_for_7%7;
if(rmd_for_7==2){
printf("Monday \n");
}
if(rmd_for_7==3){
printf("Tuesday \n");
}
if(rmd_for_7==4){
printf("Wednesday \n");
}
if(rmd_for_7==5){
printf("Thursday \n");
}
if(rmd_for_7==6){
printf("Friday \n");
}
if(rmd_for_7==0){
printf("Saturday \n");
}
if(rmd_for_7==1){
printf("Sunday \n");
}
return 0;
}
mm/dd/yyyy~~~~~~~~~~~~~~~Example: 03/04/2014
Month dd, yyyy~~~~~~~~~~~~Example: March 04, 2014
Please observe that one format starts with numbers, the other with a name. So, try this:
char buffer[32];
if(3 != fscanf(file, "%d/%d/%d", &month, &day, &year))
if(3 != fscanf(file, "%31s %d, %d", buffer, &day, &year))
abort()
else
month = mapmonthname(buffer);
/* Now do fun things... */
Given a date of birth, how would I go about calculating an age in C?
For example, if today's date is 20/04/2010 and the date of birth given is 12/08/86, then age will be 23 years, 8 months, and 8 days.
Any suggestions would be appreciated.
Thanks!
For just the year (no months/days) :
1) Format the dates to yyyymmdd
2) Subtract the date of birth from date
3) Remove the last 4 numbers
(Language agnostic)
So for your example;
date 20/04/2010
birth 12/08/1986
convert
date 20100420
birth 19860812
subtract
20100420-19860812 = 239608
drop last 4 digits
23
I'm assuming, based on your description, that you have to print out the full difference, not just years.
One part of the problem is to input the dates correctly and break them down into components, I'll assume you already know how to do that or got sample code for that.
What you need to do now is to calculate the difference. One way to do this would be to pick a reference date (e.g., Jan 1st 1900), and calculate how many days it had been until the first date and the second date, and calculate the difference in days. Then you take the difference in days and break it back into years/months/days.
Two things to notice are:
1) Take leap years into account.
2) Figure out how to translate a number of dates into months, since each month has a different number of days.
3) If you had to input times and not just dates, you could be off by a day. Similarly if time zones are input.
I would check with the instructor whether you can make a simplifying assumption about that (E.g., months are always 30, leap years are ignored, etc.). I find it hard to believe that a homework assignment would require you to deal with these correctly.
The way to approach a problem like this is to figure out how you'd do it using a pencil and paper - then formalise that into a program.
For this particular problem, that means at a high level, "subtract birth date from current date". For this subtraction, you use a variation of the same algorithm you learn for subtraction in primary school - where you start by subtracting the lower value column (in this case, "days"), borrowing from the next-higher-value column if necessary. For example, to subtract 1986-09-15 from 2010-04-10, you would do:
2010-04-10 -
1986-09-15
----------
10 is less than 15, so you have to borrow from the months column. This means that the months column goes down by one (to 3), and the days column goes up by the number of days in month 3 (March - so 31). You can now do the subtraction of the days column:
2010-03-41 -
1986-09-15
----------
-26
We can now move on to the months column. 3 is less than 9, so we have to borrow again, this time from the year. Take one off the year, and add 12 to the month (since there are always 12 months in a year), then perform the subtraction:
2009-15-41 -
1986-09-15
----------
-06-26
We can now work on the years - there's never a need to borrow here (unless you're trying to calculate the age of someone born in the future!):
2009-15-41 -
1986-09-15
----------
23-06-26
This means the difference is 23 years, 6 months, 26 days.
You can now work on turning this into a program (hint: use three seperate integer variables for years, months and days). The trickiest part is the borrow from the months column - you need to know how many days are in that month, including leap years for February.
If you're allowed to use the libraries, it's not too hard. Look at strptime, struct tm, time, and localtime. Once you have it in "broken-down" form (struct tm), it's easy to compute the difference (look at tm_yday, tm_mon, and tm_yday).
If today's date falls after the birthday, the age is the difference between the birth year and today's year. If today's date falls before the birthday, subtract 1.
/* program for calculating the age */
/* author - nitin kumar pandey */
/* mail - nitindonpandey#gmail.com */
#include<stdio.h>
#include<conio.h>
int d1,d2,d3,m1,m2,m3,y1,y2,y3;
void year(int d1,int m1,int y1,int d2,int m2,int y2);
void main()
{
clrscr();
printf("please enter the current date \n");
printf("enter the day");
scanf("%d",&d1);
printf("enter the month");
scanf("%d",&m1);
printf("enter the year");
scanf("%d",&y1);
printf("Now thank you for your cooperation \n now please enter the date of birth");
printf("enter the day");
scanf("%d",&d2);
printf("enter the month");
scanf("%d",&m2);
printf("enter the year");
scanf("%d",&y2);
year(d1,m1,y1,d2,m2,y2);
getch();
}
void year(int d1,int m1,int y1,int d2,int m2,int y2)
{
if(d2>d1)
{
m1=m1-1;
d1=d1+30;
}
if(m2>m1)
{
y1=y1-1;
m1=m1+12;
}
if(y2>y1)
{
exit(0);
}
d3=d1-d2;
m3=m1-m2;
y3=y1-y2;
printf("current age is \n day %d \n month %d \n year %d ",d3,m3,y3);
}
//Age calculation. A simple c++ program
#include<iostream>
#include<iostream>
#include<ctime>
using namespace std;
void main()
{
system("cls");
time_t theTime = time(NULL);
struct tm *aTime = localtime(&theTime);
int currentday = aTime->tm_mday;
int currentmonth = aTime->tm_mon + 1; // Month is 0 - 11, add 1 to get a jan-dec 1-12 concept
int currentyear = aTime->tm_year + 1900;
int birthday,birthmonth,birthyear;
cout<<"Enter birth year: ";
cin>>birthyear;
if(birthyear>currentyear)
{
cout<<"Current year: "<<currentyear<<endl
<<"Birht year : "<<birthyear<<endl
<<"Invalid...."<<endl<<endl;
system("pause");
main();
}
else if(birthyear<1900)
{
cout<<"Birht year should greater than 1900...."<<endl;
system("pause");
main();
}
cout<<"Enter birth month: ";
cin>>birthmonth;
if(birthmonth<1 || birthmonth>12)
{
cout<<"Birth month should be 1-12"<<endl;
system("pause");
main();
}
else if(birthyear==currentyear && birthmonth>currentmonth)
{
cout<<"Current Month/Year: "<<currentmonth<<"/"<<currentyear<<endl
<<"Birth Month/Year : "<<birthmonth<<"/"<<birthyear<<endl
<<"Future Birth Date. Invalid...."<<endl;
system("pause");
main();
}
cout<<"Enter birth day: ";
cin>>birthday;
if(birthday<1 || birthday>31)
{
cout<<"Birth day should 1-31"<<endl;
system("pause");
main();
}
else if(birthyear==currentyear && birthmonth==currentmonth && birthday>currentday)
{
cout<<"Current Day/Month/Year: "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl
<<"Birth Day/Month/Year : "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl
<<"Future Birth Date. Invalid...."<<endl;
system("pause");
main();
}
else if(birthyear%4==0 && birthmonth==2 && birthday>29)
{
cout<<"Febuary should be 1-29"<<endl;
system("pause");
main();
}
else if( (birthmonth==4 || birthmonth==6 || birthmonth==9 || birthmonth==11) && birthday>31)
{
cout<<"This month cannot have 31 days...."<<endl;
system("pause");
main();
}
int ageday,agemonth,ageyear;
if(birthmonth>currentmonth)
{
agemonth=currentmonth;
ageyear=currentyear-birthyear-1;
ageday=currentday;
}
else
{
agemonth=currentmonth-birthmonth;
ageyear=currentyear-birthyear;
ageday=currentday-birthday;
}
if(ageyear==0 && agemonth==0)
{
cout<<"your Date of Birth: "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl;
cout<<"Current Date : "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl;
cout<<"your Age : "<<ageday<<" days"<<endl;
}
else if(ageyear==0)
{
cout<<"your Date of Birth: "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl;
cout<<"Current Date : "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl;
cout<<"your Age : "<<agemonth<<" Months"<<ageday<<" days"<<endl;
}
else if(agemonth==0)
{
cout<<"your Date of Birth: "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl;
cout<<"Current Date : "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl;
cout<<"your Age : "<<ageyear<<" years"<<ageday<<" days"<<endl;
}
else if(ageday==0)
{
cout<<"your Date of Birth: "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl;
cout<<"Current Date : "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl;
cout<<"your Age : "<<ageyear<<" years"<<agemonth<<" Months"<<endl;
}
else
cout<<"your Date of Birth: "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl;
cout<<"Current Date : "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl;
cout<<"your Age : "<<ageyear<<" years"<<agemonth<<" Months"<<ageday<<" days"<<endl;
system("pause");
}
//AAW
The only issue with this code is that it doesn't factor in if you are born on leap day. there can be another if statement for that though.
// Age Calculator
time_t t = time(NULL);
struct tm tm = *localtime(&t);
int num_day;
if ( month == 1 )
{
num_day = 31;
}
if ( month == 2 )
{
num_day = 28;
}
if ( month == 3 )
{
num_day = 31;
}
if ( month == 4 )
{
num_day = 30;
}
if ( month == 5 )
{
num_day = 31;
}
if ( month == 6 )
{
num_day = 30;
}
if ( month == 7 )
{
num_day = 31;
}
if ( month == 8 )
{
num_day = 31;
}
if ( month == 9 )
{
num_day = 30;
}
if ( month == 10 )
{
num_day = 31;
}
if ( month == 11 )
{
num_day = 30;
}
if ( month == 12 )
{
num_day = 31;
}
int age_year = (tm.tm_year + 1900) - year;
int age_month = (tm.tm_mon + 1) - month;
int age_day = (tm.tm_mday) - day;
if ( age_month <= 0 )
{
age_year = (tm.tm_year + 1900) - year - 1;
age_month = 12 + (tm.tm_mon + 1) - month;
}
if ( age_day <= 0 )
{
age_month = 12 + (tm.tm_mon + 1) - month - 1;
age_day = num_day + (tm.tm_mday) - day;
}
printf("Your age: %d years %d months %d days\n", age_year, age_month, age_day);