parsing strings problem
Hi.
A little question someone might be able to help with regarding parsing strings. ive got a little function that takes a string in the format of a phone number, a space, and a first name. something like: char buffer[] = "12345678 john". i need to break the string into the number and the name. the code i have which does that, and converts the number into an int is Code:
char buffer[] = "123456 bob" printf("Phone number is: %d name is %s", number, name) to just check that it has actually been split into the 2 parts correctly. and sure enough, i get output like: "phone number is 123456 name is bob". BUT... if im passing 'buffer' into the function as a parameter i get problems. my code is exactly the same except instead of declaring buffer to = '123456 bob' inside the function like the code above, im passing it in. EG void parseFunc (char buffer[]) thats the only change in the code, yet when i run this version the output i get is: "phone number is 123456 name is (null)". what am i doing wrong? why do i get a 'null" value when i parse a string thats been passed in, and not when i declare a string within the function? any help would be much appreciated! Thanks |
if you try to work on the string 'burrer' you'll run into problems because its static.
|
another word of advise: never use the printf function to print strings (%s). always use puts() or something that doesnt attempt to format it.
|
Thanks for the puts vs printf tip.
so how do i go about parsing a string thats entered by the user, or passed in, as oppsed to the case above where its declared as already containing....something? |
You have to do 2 things differently:
1) declare your variables as arrays (char num[6], name[20]). 2) Use strcpy() to store strtok()'s results (strcpy(num, strtok(buffer, " ");) That should fix all your problems. |
Quote:
If you already know the format of the input why not use the appropriate scanf() function? |
Quote:
Even with your scanf() idea he'd have to store the results, be it by introducing "artificial limits" or by dynamically allocating the memory. |
All times are GMT -5. The time now is 04:01 AM. |