-
newbie strtok funcn
Hi,
The problem is input the phone string, break it into tokens,take area code convert it into int,append the remaining (3+4)strings ,convert into long int and display the area code and phonenumber.
Well,my problem is for the remaining strings (ie.phone num) the ouput is 0 when converted to long int.Please tell me where I am going wrong!!
Help ,I am just frustrated ..such small thing is now becoming a big stuff for me........
Code:
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char phone[15]; char area[7]; char num[10]; char* tokenPtr;
int areaCode;
long int pnum;
cout << "Enter a phone number [(###) ###-####]: ";
cin.getline(phone, 15);
while(tokenPtr!=NULL)
{
tokenPtr = strtok(phone, "()- "); //for tokenising the phonenum.
strcpy(area,tokenPtr); //copy the first part into area
areaCode = atoi(area);//converting strign to integer
strcat(num, tokenPtr);//appending the remaining strings to num
tokenPtr = strtok(NULL, "()- ");
}
cout << areaCode << atol(num) << endl;
return 0;
}
-
No need for the loop.
Just a general hint of advice-
When you have problems in your code, output the values to the screen at each step so you can see what they are. Many times this will lead to a solution. For example: in your program if you would have printed out the token each time you tokenized I think you might have been able to figure out what was wrong.
Took out the loop and switched a few things around.
Code:
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char phone[15];
char num[10];
char* tokenPtr;
int areaCode;
cout << "Enter a phone number [(###) ###-####]: ";
cin.getline(phone, 15);
tokenPtr = strtok(phone, "()- "); //for tokenising the phonenum.
areaCode = atoi(tokenPtr);//converting strign to integer
tokenPtr = strtok(NULL, "()- ");
strcpy(num, tokenPtr);
tokenPtr = strtok(NULL, "()- ");
strcat(num, tokenPtr);
cout << areaCode << " " << atol(num) << endl;
return 0;
}