I have an int that has dashes in. It has to remain int and I cant use any arrays. For example, I need 34-2345-21 to be 342345-21. Any help on a way to achieve this?
I have an int that has dashes in. It has to remain int and I cant use any arrays. For example, I need 34-2345-21 to be 342345-21. Any help on a way to achieve this?
Can you be more specific about how you're going to use it?
Kampai!
Ooops, I did that wrong. I meant 34234521. Its a product number that I am storing in a structure. It has be an int.
The only way i can think of is to store the number in a character array , use strtok() to get rid of the dashes and finally strtol() to convert it to a long number.
But you said you can't use arrays...
My Tutorials :
- Bad programming practices in : C
- C\C++ Tips
(constrcutive criticism is very welcome)
- Brain Cell
>>Its a product number that I am storing in a structure. It has be an int.
Do you have to put the dashes back at any point? Are product numbers consistent in the placement of dashes? Removing the dashes is pretty simple, but if need to put them back then you have to have a way to determine where they were to begin with.
Kampai!
Yes, the dashes must be placed back. Also the product number is the same all the time, 2 digits, dash, 4 digits, dash, 2 digits.
Something like this?
Code:#include <stdio.h> #include <stdlib.h> long int pctoi(const char *pc) { long int ret = 0; char *end; ret = strtol(pc, &end, 0); ret = (ret * 10000) + strtol(end + 1, &end, 0); ret = (ret * 100) + strtol(end + 1, &end, 0); return ret; } void printpc(long int pc) { printf("%2d-%4d-%2d\n", pc / 1000000, pc / 10000, pc % 100); } int main(void) { const char *from = "34-2345-21"; long int to = 34234521; printf("%ld\n", pctoi(from)); printpc(to); return 0; }
Kampai!