So I need to be able to input a string as a phone number like so: (555)-444-3333. After that I need to use strtok to remove the parentheses and dashes, and convert the strings area code and the rest of the phone number to just integers and print them out all together My problem is using strtok to get rid of the ( , because if I don't the area code will just print 0 when it's converted to an int. Here's what I have:
int main()
{
phone[14];
int* area_code;
int* digits;
int* i, j;
printf("Enter a phone number: ");
scanf("%s", phone);
strtok( phone, "(" );
area_code = strtok( phone, ")" );
j = atoi(area_code);
printf("%d", j);
while((digits = strtok(NULL, "-")) != NULL )
{
i = atoi(digits);
printf("%d", digits);
}
return 0;
}
The problem is right here:
strtok( phone, "(" );
area_code = strtok( phone, ")" );
Because the second call passes a non-NULL pointer, it doesn't continue processing the first string, it starts over beginning at the pointer passed, which is now a string of length zero.
In any case, overwriting the string you are parsing is bad style. If you use strtol
, a single call will give you BOTH the numeric value of a group of digits AND a pointer following the digits, where you can start processing the next group of digits.
But if you just are going to print the digits back out, you don't need a numeric conversion at all. Just remove all punctuation.
Despite having 5/6 characters the same, strtok
is not part of the str
-to
-x family of functions. Those are strtol
returning a long integer, and strtod
returning a double.