The question assume
typedef struct {
int day;
int month;
int year;
} Date;
Date mfgDate = {17, 10, 2016}, expiryDate;
printf("%d-%d-%d", mfgDate.day, mfgDate.month, mfgDate.year);
By doing this i can display the date to the form of 17-10-2016, the question requires me to display the date in the form of DD-MMM-YYYY which is 17-OCT-2016, how can i do that? the question provides a tip which is to use switch statement but i can't seems to find out how, thanks a lot for help.
You could use strftime() for that:
char buffer[BUFFER_SIZE];
errno=0; //clear errno since we need it to detect errors in strftime()
//tm_year is years since 1900
//%d prints the day of the month, %B or %b the month name according to the locale
//and %Y prints the year, results in the format DD-MMMM-YYYY
int r = strftime
(buffer, sizeof buffer, "%d-%b-%Y", &(struct tm){.tm_year=2016-1900, .tm_mon=9, .tm_mday=17} );
if(!r && errno)
{
//do some error handling here
}
printf("%s\n",buffer);
If you are just starting with C and have not learned about arrays, a switch statement is a viable choice, just for the execise
const char* monthname(int month)
{
switch (month) {
case 1: return "JAN";
case 2: return "FEB";
// you can fill the remaining month yourself here
case 12: return "DEC";
// handle the error case
default: return "???";
}
}
to print your date then use:
printf("%d-%s-%d", mfgDate.day, monthname(mfgDate.month), mfgDate.year);
Simply have months names in the table.
char *months[] = {"JAN", "FEB","MAR", ......};
printf("%d-%s-%d", mfgDate.day, months[mfgDate.month - 1], mfgDate.year);
Related
I'm trying to create a code that accepts a date, however I want to give the user the ability to enter the date as dd/mm/yyyy or dd-mm-yyyy. My code is below, I tried to use OR but it does not work
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main ()
{
int dayA, monthA, yearA,
printf("First date in format DD/MM/YYYY or DD-MM-YYYY: ");
scanf("%d/%d/%d" || "%d-%d-%d", &dayA, monthA, yearA);
Here is a simple way to do it. It inputs into a string, and then checks if one of the format methods works. It's always essential to check the return value from the scanf function family, to know if the conversion succeeded.
#include<stdio.h>
int main(void)
{
int dayA, monthA, yearA;
puts("Enter a date dd/mm/yyyy or dd-mm-yyyy");
char datestr[32];
if(fgets(datestr, sizeof datestr, stdin) != NULL) {
if(sscanf(datestr, "%d/%d/%d", &dayA, &monthA, &yearA) == 3 || // added missing &
sscanf(datestr, "%d-%d-%d", &dayA, &monthA, &yearA) == 3) {
printf("Date is day %d, month %d, year %d\n", dayA, monthA, yearA);
}
}
}
Here are two runs of the program:
Enter a date dd/mm/yyyy or dd-mm-yyyy
23/4/2020
Date is day 23, month 4, year 2020
Enter a date dd/mm/yyyy or dd-mm-yyyy
23-4-2020
Date is day 23, month 4, year 2020
I am building a C program and I need to use time separately and also the date separately. I want to do this without using the structure struct tm since I have to send the time and the date to different columns in my database table called Logs:
int main(){
duration = clock() - duration;
double Duration = ((double)duration)/CLOCKS_PER_SEC;
char* IPaddr = inet_ntoa(newAddr.sin_addr);
int PortNo = ntohs(newAddr.sin_port);
printf("\n%s %s %d %f\n", task, IPaddr, PortNo, Duration);
printf("now: %d-%d-%d %d:%d:%d\n",tm.tm_mday,tm.tm_mon+1,tm.tm_year+1900,tm.tm_hour,tm.tm_min,tm.tm_sec);
if (mysql_query(con, "INSERT INTO Logs(ClientIP, ClientPort, Job_type, SubmissionTime, SubmissionDate, Duration)
VALUES(%s, %d, %s, %, %, %f)")) {
finish_with_error(con);
}
return 0;
}
You might want to declare two character arrays, one for the date string and one for the time string, and call strftime twice to construct them.
Something like this:
char SubmissionDate[20], SubmissionTime[20];
strftime(SubmissionDate, sizeof(SubmissionDate), "%Y-%m-%d", &tm);
strftime(SubmissionTime, sizeof(SubmissionTime), "%H:%M:%S", &tm);
In College we had to write a program with structs, enums and unions to display a date,
like 1.September 2014.
I had some problems with printing an enum. I found some solutions in this forum and finally I've got no console errors anymore. But Everytime I try to run my Program it crashes.
Maybe someone of you knwos what's causing the crash:
#include <stdio.h>
enum Monate{JANUAR = 1,
FEBRUAR = 2,
MAERZ = 3,
APRIL = 4,
MAI = 5,
JUNI = 6,
JULI = 7,
AUGUST = 8,
SEPTEMBER = 9,
OKTOBER = 10,
NOVEMBER = 11,
DEZEMBER = 12 };
union Monat{
enum Monate alsMonat;
char alsZahl;
char alsString[10];
};
struct Datum {
char tag;
union Monat monat;
short jahr;
};
const char* welcherMonat(enum Monate meinMonat){
switch(meinMonat){
case JANUAR: return"Januar";
break;
case FEBRUAR: return"Februar";
break;
case MAERZ: return"Maerz";
break;
case APRIL: return"April";
break;
case MAI: return"Mai";
break;
case JUNI: return"Juni";
break;
case JULI: return"Juli";
break;
case AUGUST: return"August";
break;
case SEPTEMBER: return"September";
break;
case OKTOBER: return"Oktober";
break;
case NOVEMBER: return"November";
break;
case DEZEMBER: return"Dezember";
break;
}
}
void ausgabe(struct Datum *datum){
char month[10]=" ";
printf("Tag: %c\n",(*datum).tag);
enum Monate monat2=(*datum).monat.alsMonat;
printf("Monat: %s\n",welcherMonat(monat2));
printf("Jahr: %d\n\n",(*datum).jahr);
}
int main(int argc, char** argv){
struct Datum Geburtstag = {'3',AUGUST,1995};
struct Datum Heute = {'3','12',2014};
struct Datum Millenium = {'1',1,2000};
ausgabe(&Geburtstag);
ausgabe(&Heute);
ausgabe(&Millenium);
return 0;
}
Use GDB. It is the Gnu DeBugger. Compile your code with the -g option enabled, and it will include all of the proper debugging symbols. You can then use GDB to put a manual break in the program and step through it one line at a time, look at variables, and see exactly where it is crashing.
How can you have a multi-character char like this:
struct Datum Heute = {'3','12',2014};
Doesn't your compiler throw a warning for this? It should ideally
It seems like I overlooked the MultiCharacter warning...
When I choose a one-character month it still freezes at the second print, when I want to print the date by using a char as month. The other two types of printing the month(by enum) work totally fine.
Our task was to print three different dates by using all three kinds of month-printing.
I think I know the Problem:
enum Monate monat2=(*datum).monat.alsMonat;
printf("Monat: %s\n",welcherMonat(monat2));
when I give the function a char instead of an enum, "monat2" is empty.
But how could I check whether I give him a char or an enum?
I wrote a quick program (Calculating wages) to help me stay up to speed. For some reason when I compile this I keep getting the error "53: syntax error before ';' token"
#include
int main()
{
#define week 7;
#define year 365;
int jan,feb,mar,apr,may,june,july,aug,sep,oct,nov,dec;
int wage; /* Upgrade to float in future */
char input,month;
int holder;
jan=mar=may=july=aug=oct=dec=31;
apr=june=sep=nov=30;
feb=28;
for(;;)
{
if(input='y')
{
#define YEAR 366;
break;
}
else if(input='n')
{
break;
}
else
{
printf("Unable to understand input");
}
}
printf("Enter wage/day in pounds.\n?\n");
scanf("%d",&wage); /* unsure if I need to get string and then use atoi */
printf("Wage per day:\t%d\n",wage);
printf("Wage per week:\t%d\n",wage*7);
printf("Wage per month:\t%d\n",wage*30);
holder=YEAR;
printf("Wage per year:\t%d\n",wage*holder);
printf("As months have varying day amounts, if you wish to view a specific month type:\n");
printf("A-Jan\nB-Feb\nC-Mar\nD-Apr\nE-May\nF-June\nG-July\nH-Aug\nI-Sep\nJ-Oct\nK-Nov\nL-Dec\nor type X-to EXIT");
month=getchar();
if((month=='A')||(month=='C')||(month=='E')||(month=='G')||(month=='H')||(month=='J')||(month=='L')){
printf("Wage for this month will be:\t%d",wage*31);
}
else if((month=='D')||(month=='F')||(month=='I')||(month=='K')){
printf("Wage for this month will be:\t%d",wage*30);
}
else if((month=='B')&&(year==365)){
printf("Wage for this month will be:\t%d",wage*28);
}
else if((month=='B')&&(year==366)){
printf("Wage for this month will be:\t%d",wage*29);
}
else if(month=='X'){
exit(1);
}
return 0;
}
No matter how many times I read through it I just can't manage to see what I'm doing incorrectly.
As a side note, if anybody feels like screaming/giving pointers about my style go ahead as I appreciate any tips that can lead to the improvement of my skills.
Thanks everyone, that was an overwhelmingly fast response, I've got the code compiled correctly so now I can start debugging the runtime errors (Before anyone mentions it. Yes I do understand the need to flush after input)
One error (though not the one that immediately got you, it seems) is this line:
exit 1;
In C, exit is a regular function, and so you have to call it like this:
exit(1);
As others have pointed out, your use of || is also incorrect, though that is probably giving you warnings (if anything) and not errors.
You cannot do
if (month=='A'||'C'||'E'||'G'||'H'||'J'||'L'){
...
}
This way month=='A'||'C'||'E'||'G'||'H'||'J'||'L' you are comparing the wrong values, i.e. <bool> || <char> || <char> ||..., which gives you an invalid syntax.
Try this instead,
if (month=='A' ||
month=='C' ||
month=='E' ||
month=='G' ||
month=='H' ||
month=='J' ||
month=='L') {
...
}
However, as mentioned by #danfuzz, the issue seems to lie elsewhere...
There are many catastrophic problems with your code, but most of them (besides the exit 1 bit) are formally compilable. They're just not doing what you think they're doing.
However, you state that you get a compilation error well before that exit 1 line. If that is the case, then it must be caused by something you aren't showing us, since there's no ; on line 53. My guess would be that year is defined as a macro that contains ;.
EDIT: In the comments you said that you have defined year as 365. I suspect that you did this
#define year 365;
This is what's causing the error. Get rid of that ; after 365. However, if that's the case I still don't get why you would compare your year to 365 or 366 if you already defined it to be 365 specifically.
EDIT: So, it is exactly as I guessed. You don't need those ; after #define statements for manifest constants. This is your error. Macros are replaced by textual substitution meaning that currently your
if((month=='B')&&(year==365)){
gets translated into
if((month=='B')&&(365;==365)){
which is what causes the original error. If you want to define year as a macro constant that stands for 365, it should be
#define year 365
The same applies to week, although you are not using it anywhere in your code.
Your sintax is wrong, the correct way to write that is:
if((month=='A')||(month=='C')||(month=='E')||(month=='G')||(month=='H')||(month=='J')||(month=='L')){
printf("Wage for this month will be:\t%d",wage*31);
}
and so on. But you may want to consider the switch which is probably more easy to read.
switch( month ) {
case 'A':
case 'C':
case 'E':
case 'G':
case 'H':
printf( "statement A\n");
break;
case 'K':
case 'D':
case 'F':
printf( "statement B\n");
break;
case 'B':
if( year == 365) {
printf( "something else\n" );
} else if( year == 366 ) {
printf( "something else\n" );
} else {
printf( "Unexpected year %d\n", year );
}
break;
case 'X':
return -1; /* Note here return... not exit! */
default:
printf( "Why am I here?\n" );
break;
}
Now that you edited another error is #define YEAR 365;
Get rid of that ';'. You may prefer defining that as int instead of using a precompiler define, expecially if you are going to change its value
#include<time.h>
#include<stdio.h>
int main(void)
{
time_t timer;
int i;
char mon[4];
char *ti=0;
ti=asctime(localtime(&timer));
ti=ti+4;
for(i=0;i<3;i++)
{
mon[i]=*ti++;
}
mon[3]='\0';
timer=time(NULL);
printf("The current time is %s\n",mon);
return 0;
}
Hi, Can anyone expalin why asctime returns wrong time-pointer sometimes.Iam using 'mon' to store the month from asctime string and when printing it on the console,it displays sometimes 'Mar' and sometimes some other month.
You are using timer without initializing it. Before calling localtime, try:
time(&timer);
Also, a simpler way to do it would be:
ctime(&timer);