tokenizing cstrings

Hey,

I'm trying to play around with a few functions to get the hang of them.

Basically, here I want to create a function that reads a phone number in the form of 111-222-3333 and tokenize the string with "-" as the delineater then use strcat to concatenate the string into a full phone number and print it.

This is what I've done so far, but it doesn't seem to be working. Any suggestions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	char stringA[80];
	char finishedNum[11];
	cout << "enter a phone number in the form 555-555-5555" << endl;
	cin.getline(stringA, 80);

	char * tPntr = strtok(stringA, "-");
	
	while (tPntr != NULL)
	{
		cout << tPntr << endl;
		tPntr = strtok(NULL, "-");
		strcat(finishedNum, tPntr);
		
	}
	cout << finishedNum;
closed account (48T7M4Gy)
Have you looked at the tutorials here?
http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok and the accompanying sample program?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}
Thanks, I did look at that.

My code is very similar to that, im just trying to concatenate the individual tokens so I can print the phone number as a single string.
You need to swap lines 11 and 12 otherwise you overwrite tPntr before you have added it to finishedNum.
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="111-222-333-AxC-78fgh/";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str,"-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, "-");
  }
  return 0;
}
Splitting string "111-222-333-AxC-78fgh/" into tokens:
111
222
333
AxC
78fgh/
C:
1
2
3
4
5
6
7
8
// invariant: source and destination may overlap as long as dest <= srce
char* remove_sep( const char* srce, char sep, char* dest )
{
    char* p = dest ;
    for( ; *srce ; ++srce ) if( *srce != sep ) *p++ = *srce ;
    *p = 0 ; // null terminate
    return dest ;
}

http://coliru.stacked-crooked.com/a/61fbea232600aeb0
Topic archived. No new replies allowed.