Mail Archives: djgpp/2000/08/06/08:18:08
only4usa <only4usa AT x-treme DOT gr> wrote:
> I have this program that converts a string to date. Most of the time it
> does it correctly but some times it gives wrong values. I run the
> program from a DOS box (i can only run it from a DOS box). That
> subroutine the main program calls it about 2000 times per execution and
> sometimes it reports wrong values. Can someone help me?
You seem to have a misunderstanding of how strings work in C, but
that's no surprise since most users have a problem with strings to
start with. I've marked up your code below with some comments I hope
will help.
A string is basically an array of chars, with the last char set to
null to mark the end of the string. A good text book will explain
strings in detail, or look to a C language group such as comp.lang.c.
There is no checking on the validity of the input string. What do you
expect to happen if the input string is "abcd", for example? At least
use strlen() to test the length, and do not attempt to read beyond
this. You could also do some sanity checking on the values returned
from atoi().
> Here is the program:
> void date_str(char *string, int *day, int *month, int *year)
Since there is no intention to write to string, declare it as const:
void date_str(const char *string, int *day, int *month, int *year)
> {
> int i;
> char c, c1[2], c2[2], c3[4];
There needs to be space for the terminating null of each string, and
how about use more descriptive variable names:
char c, dd[3], mm[3], yyyy[5];
> for(i = 0;i < 2;i++)
> {
> c = string[i];
> c1[i] = c;
> }
> for(i = 2;i < 4;i++)
> {
> c = string[i];
> c2[i - 2] = c;
> }
> for(i = 4;i < 8;i++)
> {
> c = string[i];
> c3[i - 4] = c;
> }
> if (c1[0] == '0')
This is unecessary, atoi() handles leading zeros without a problem.
> {
> c = c1[1];
> *day = atoi(&c);
and in any case, &c is a pointer to a single char, not a string, so
this will not do what you want.
> }
> else
> *day = atoi(c1);
> if (c2[0] == '0')
> {
> c = c2[1];
> *month = atoi(&c);
> }
Ditto.
> else
> *month = atof(c2);
atof() ? You probably meant atoi().
> *year = atoi(c3);
> }
Hope that helps, and good luck with this. ;-)
- Raw text -