Reputation: 13
This code gives an output:
in Xcode console: for 2015-12-23
output date: Wed 2015-12-23
on linux terminal: for 2015-12-23
output 2015-08-26
(before 2015 it's just a space)
Can anybody tell me how it's possible? I tried puts() method when printing a date, but it didn't help too.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include <string.h>
// Functions declaration
int StringLength(char *string);
bool IsDate (char myString[100], int length);
bool IsNumber (char myString[100], int length);
bool IsPrime (char myString[100]);
bool IsPalindrome (char myString[100], int length);
// Global variables declaration
int i;
int code;
bool tmp = true;
bool date = true;
char buffer[3];
int main(int argc, const char * argv[]) {
char unknownString[100];
printf("Insert a date string: ");
code = scanf("%100s", unknownString);
while (code == 1) {
date = IsDate(unknownString, strlen(unknownString));
printf("date: %s %s\n", buffer, unknownString);
printf("Insert a date string: ");
code = scanf("%100s", unknownString);
}
return 0;
}
bool IsDate (char myString[100], int length) {
tmp = true;
struct tm timeString;
// Only unknownString == 10 could be date because of the format DDDD-DD-DD which has 10 characters
if (length == 10) {
// Without this condition, IsDate would be true with format 1234x56x78
if (myString[4] == '-' && myString[7] == '-') {
timeString.tm_year = atoi(myString) - 1900;
timeString.tm_mon = atoi(&myString[5]) - 1;
timeString.tm_mday = atoi(&myString[8]);
timeString.tm_hour = 0;
timeString.tm_min = 0;
timeString.tm_sec = 1;
timeString.tm_isdst = 0;
if (mktime(&timeString) == -1) {
fprintf(stderr, "Unable to make time.\nError in IsDate function.\n");
exit(1);
}
else {
strftime(buffer, sizeof(buffer), "%c", &timeString);
}
}
else {
tmp = false;
}
}
// If length is different than 10
else {
tmp = false;
}
return tmp;
}
Upvotes: 1
Views: 96
Reputation: 144520
Buffer buffer
is too short for a locale’s appropriate date and time representation. Make this buffer at least 32 bytes.
char buffer[32];
I believe you found a bug in Xcode, this code:
strftime(buffer, sizeof(buffer), "%c", &timeString);
Should never produce Wed
in buffer
. It should either produce nothing as it does in terminal or clip the name to 2 characters We
. If you are only interested in the weekday abbreviation, make the buffer at least 4 bytes and use format "%a"
.
Upvotes: 1