Quote:
|
i might be an idiot but i dont know what the problem is
|
First:
The first parameter of
strcat() must be a null-terminated string. Since you declare
storage on the stack without initialization, it contains random data, i.e. it's not a null terminated string. To fix this, explicitly set the first entry of
storage to '0', i.e.
Code:
char storage[200];
storage[0] = 0; // storage is a null terminated string of length 0
or simply
Code:
char storage[200] = {0}; // this actually sets all entries to 0, not just the first one
Secondly:
When I compile your code with GCC, I get the following warning:
Quote:
test.c:12:17: warning: passing argument 2 of ‘strcat’ makes pointer from integer without a cast [-Wint-conversion]
strcat(storage,c);
|
Indeed, the signature of strcat is as follows:
Code:
char * strcat ( char * destination, const char * source );
So the second parameter must be a pointer to char (= C string). But you pass a
char as second parameter.
Compilation doesn't fail because the character gets implicitly casted to an address, i.e. if your char is '0' == 48, 48 is interpreted as an address. But that's probably not what you want; thus, you should get a warning.
If you want to fix your own code, I see two options:
Replace
with
Code:
char tmp[] = {c, 0}; strcat(storage, tmp);
I.e. create a temporary string that only has one character, namely
c (and null termination!), then pass that string as second parameter.
Note that
Code:
strcat(storage, &c);
wouldn't work because then there's no null termination (the code would compile without warnings though).
Or don't use
strcat():
Code:
int j = 0;
for (i = 0; date[i] != 0; i++) {
char c = date[i];
if(c != '.'){
storage[j] = c;
++j;
}
}
storage[j] = 0; // don't forget 0-termination!
maxi39's code is more complicated because it doesn't use
atoi(). But this can be done more efficiently, you don't need the
longPow() function:
Code:
int getdate(const char *date){
int number = 0;
while (*date) { // aborts if *date == 0
if (isdigit(*date)) { // skip anything that is not a digit
number *= 10; // move previous digits to the left
number += *date - '0'; // add new digit
}
++date;
}
return number;
}
The idea of the code is as follows: Let's say you want to turn the string "123" into an
int; consider the string digit by digit, from left to right.
The first digit is 1,
number = 1
Since there are more digits, move "1" to the left by multiplying
number with 10:
10 * number = 10
Now add the next digit, 2:
number = 10 + 2 = 12
Again, since there are more digits, move the previous digits one to the left:
10 * number = 120
And add the next digit:
number = 120 + 3 = 123
Since there are no more digits in this example, return
number
In general, if you have an integer A and want to append a digit D to the right, use
A' = 10 * A + D.