473,796 Members | 2,517 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strtok problem

Hi,
I need to split the value stored in a string and store them to another
charrecter array.I am using strtok function.But i am getting invalid
output when there is no value between delimiter

my code
#include<stdio. h>
#include<string .h>
#include<stdlib .h>
void main()
{

char *pch;
char *parameters[4];
int paramcount=0;

char b[]="mani,raju,mus a,kumar";

pch=strtok(b,", ");
while (pch != NULL)
{
//parameters[paramcount]=pch;
parameters[paramcount]=(char*)malloc( strlen(pch) + 1);
strcpy(paramete rs[paramcount],pch);
paramcount++;
pch = strtok (NULL, ",");
}//while (pch != NULL)

for(int t=0;t<4;t++)
printf("\n%s\n" ,parameters[t]);

}
the above code works fine.when i change the input as follows
char b[]="mani,,,kum ar"
The output is not correct.
How to free the memory allocated?
how to handle strtok when there is no value between delimiter

Regards,
Manikandan

Mar 29 '06 #1
5 7711
pl**********@gm ail.com wrote:
[snip]
pch=strtok(b,", "); [snip] the above code works fine.when i change the input as follows
char b[]="mani,,,kum ar"
The output is not correct.
How to free the memory allocated?
how to handle strtok when there is no value between delimiter


I am convinced that the main purpose of the strtok function being
in the library is to catch new coders in the knees.

Carefully read up on the strtok function in your compiler's docs.
Note what happens when there are multiple delimeters with
nothing between them. So, your "not working" input will be
equivalent to

char b[]="mani,kumar "

that is, there's no way for you to use strtok to get those missing
fields in the middle.

Also, read up in your docs about the various warnings and caveats
about using strtok. The security warning that should be there, for
example. And the warning about a static variable being used so that
multiple overlapping calls with different strings to tokenize will
interfere with eachother.

My opinion: Don't use strtok. Roll up your own parsing class,
preferably using std::string instead of char arrays. But even if
you can't use std::string, drop the use of strtok.

Write yourself a class that takes your input, copies it to an
internal buffer, then parses it out to a vector of tokens. Give
it the behaviour you need it to have with regard to missing
entries. Make sure you follow all the "motherhood " rules
about class design such as the rule of 3, and so on. Then
give it a small number of "get" funcs that pull out the number
of items in the vector, and the "nth" item in the list. You
can then have a really good time deciding what to do about
such things as asking for an element past the end (the
7th element when there are only 4, as an example.)

You can even have such things as multiple delimeters,
delims that are more than one char, even calculated delims
that depend on rules such as a space after a period is a
delim, but a space after anything else is not.
Socks

Mar 29 '06 #2
pl**********@gm ail.com wrote:
the above code works fine.when i change the input as follows
char b[]="mani,,,kum ar"
The output is not correct.
Well, that depends on what "correct" means. According to the definition
of strotk, the new input has two data fields, separated by three commas.
strtok swallows all consecutive occurrences of characters in the
delimiter string.
How to free the memory allocated?
Same way you allocated it: step through the array and call delete[] on
each allocated block.
how to handle strtok when there is no value between delimiter


strtok doesn't do that. You can use strcspn if you don't mind doing a
little more bookkeeping. Or you can use the STL algorithm find_first_of
to find the next occurrence of the delimiter in a C string. Or, at the
cost of a little more overhead, copy the text into a C++ string object,
and use its member function find_first_of.

--

Pete Becker
Roundhouse Consulting, Ltd.
Mar 29 '06 #3
Puppet_Sock wrote:
pl**********@gm ail.com wrote:
[snip]
pch=strtok(b,", ");

[snip]
the above code works fine.when i change the input as follows
char b[]="mani,,,kum ar"
The output is not correct.
How to free the memory allocated?
how to handle strtok when there is no value between delimiter


I am convinced that the main purpose of the strtok function being
in the library is to catch new coders in the knees.

Carefully read up on the strtok function in your compiler's docs.
Note what happens when there are multiple delimeters with
nothing between them. So, your "not working" input will be
equivalent to

char b[]="mani,kumar "

that is, there's no way for you to use strtok to get those missing
fields in the middle.

Also, read up in your docs about the various warnings and caveats
about using strtok. The security warning that should be there, for
example. And the warning about a static variable being used so that
multiple overlapping calls with different strings to tokenize will
interfere with eachother.

My opinion: Don't use strtok. Roll up your own parsing class,
preferably using std::string instead of char arrays. But even if
you can't use std::string, drop the use of strtok.

Write yourself a class that takes your input, copies it to an
internal buffer, then parses it out to a vector of tokens. Give
it the behaviour you need it to have with regard to missing
entries. Make sure you follow all the "motherhood " rules
about class design such as the rule of 3, and so on. Then
give it a small number of "get" funcs that pull out the number
of items in the vector, and the "nth" item in the list. You
can then have a really good time deciding what to do about
such things as asking for an element past the end (the
7th element when there are only 4, as an example.)

You can even have such things as multiple delimeters,
delims that are more than one char, even calculated delims
that depend on rules such as a space after a period is a
delim, but a space after anything else is not.
Socks


Better yet, use John Bandela's Boost tokenizer (www.boost.org). From
there, you'll likely discover other boost delicacies that will make the
library almost indispensable.

-York
Mar 29 '06 #4
In article <11************ **********@g10g 2000cwb.googleg roups.com>,
pl**********@gm ail.com wrote:
Hi,
I need to split the value stored in a string and store them to another
charrecter array.I am using strtok function.But i am getting invalid
output when there is no value between delimiter

my code
#include<stdio. h>
#include<string .h>
#include<stdlib .h>
void main()
{

char *pch;
char *parameters[4];
int paramcount=0;

char b[]="mani,raju,mus a,kumar";

pch=strtok(b,", ");
while (pch != NULL)
{
//parameters[paramcount]=pch;
parameters[paramcount]=(char*)malloc( strlen(pch) + 1);
strcpy(paramete rs[paramcount],pch);
paramcount++;
pch = strtok (NULL, ",");
}//while (pch != NULL)

for(int t=0;t<4;t++)
printf("\n%s\n" ,parameters[t]);

}
the above code works fine.when i change the input as follows
char b[]="mani,,,kum ar"
The output is not correct.
How to free the memory allocated?
how to handle strtok when there is no value between delimiter


I'm thinking your confused as accidentally posted this in a C++
newsgroup instead of a C newsgroup. Could that be the case? If not...

I suggest you use some standard C++ components:

#include <algorithm> // for copy & find
#include <iostream> // for cout
#include <iterator> // for ostream_iterato r
#include <string>
#include <vector>

using namespace std;

int main()
{
//char b[]="mani,raju,mus a,kumar";
char b[]="mani,,,kumar" ;

vector<string> vec;
const char* first = b;
const char* last = b + strlen( b );
while ( first != last ) {
const char* next = find( first, last, ',' );
vec.push_back( string( first, next - first ) );
first = min( next + 1, last );
}
copy( vec.begin(), vec.end(),
ostream_iterato r<string>( cout, "\n" ) );
}
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Mar 30 '06 #5
In article
<11************ **********@g10g 2000cwb.googleg roups.com>,
pl**********@gm ail.com wrote:
Hi,
I need to split the value stored in a string and store them to another charrecter array.I am using strtok function.But i am getting invalid
output when there is no value between delimiter

my code
#include<stdio. h
#include<string .h
#include<stdlib .h
void main()
{

char *pch;
char *parameters[4];
int paramcount=0;

char b[]="mani,raju,mus a,kumar";

pch=strtok(b,", ");
while (pch != NULL)
{
//parameters[paramcount]=pch;
parameters[paramcount]=(char*)malloc( strlen(pch) + 1);
strcpy(paramete rs[paramcount],pch);
paramcount++;
pch = strtok (NULL, ",");
}//while (pch != NULL)

for(int t=0;t<4;t++)
printf("\n%s\n" ,parameters[t]);

}
the above code works fine.when i change the input as follows
char b[]="mani,,,kum ar"
The output is not correct.
How to free the memory allocated?
how to handle strtok when there is no value between delimiter

I'm thinking your confused as accidentally posted this in a C++
newsgroup instead of a C newsgroup. Could that be the case? If not...

I suggest you use some standard C++ components:

#include <algorithm> // for copy & find
#include <iostream> // for cout
#include <iterator> // for ostream_iterato r
#include <string>
#include <vector>

using namespace std;

int main()
{
//char b[]="mani,raju,mus a,kumar";
char b[]="mani,,,kumar" ;

vector<string> vec;
const char* first = b;
const char* last = b + strlen( b );
while ( first != last ) {
const char* next = find( first, last, ',' );
vec.push_back( string( first, next - first ) );
first = min( next + 1, last );
}
copy( vec.begin(), vec.end(),
ostream_iterato r<string>( cout,
"\n" ) );
}
--
Magic depends on tradition and belief. It does not welcome
observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.

Mar 30 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
414
by: Ram Laxman | last post by:
Hi all, I have written the following code: /* strtok example */ #include <stdio.h> #include <string.h> static const char * const resultFileName = "param.txt";
3
2638
by: alef | last post by:
Hi, I have the following code which is driving me crazy. I compile it on MacOSX and it keeps crashing upon entering a command in the program (ran trough gdb) pwd Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_PROTECTION_FAILURE at address: 0x00000000
12
1840
by: ern | last post by:
I'm using it like this: char * _command = "one two three four"; char * g_UserCommands; const char * delimeters = " "; g_UserCommands = strtok(_command, delimeters); g_UserCommands = strtok(g_UserCommands, delimeters); g_UserCommands = strtok(g_UserCommands, delimeters); g_UserCommands = strtok(g_UserCommands, delimeters); //Then I print each entry of g_UserCommands.
13
4927
by: ern | last post by:
I'm using strtok( ) to capture lines of input. After I call "splitCommand", I call strtok( ) again to get the next line. Strtok( ) returns NULL (but there is more in the file...). That didn't happen before 'splitCommands' entered the picture. The problem is in splitCommands( ) somehow modifying the pointer, but I HAVE to call that function. Is there a way to make a copy of it or something ? /* HERE IS MY CODE */ char *...
20
17244
by: bubunia2000 | last post by:
Hi all, I heard that strtok is not thread safe. So I want to write a sample program which will tokenize string without using strtok. Can I get a sample source code for the same. For exp: 0.0.0.0--->I want to tokenize the string using delimiter as as dot. Regards
2
2090
by: manochavishal | last post by:
Hi I am writing a Program in which i get input as #C1012,S,A#C1013,S,U I want to get C1012,S,A using strtok and then pass this to function CreateCopies which will further strtok this (C1012,S,A) and store the required
4
2736
by: Michael | last post by:
Hi, I have a proble I don't understand when using strtok(). It seems that if I make a call to strtok(), then make a call to another function that also makes use of strtok(), the original call is somehow confused or upset. I have the following code, which I am using to tokenise some input which is in th form x:y:1.2: int tokenize_input(Sale *sale, char *string){
29
2588
by: Pietro Cerutti | last post by:
Hello, here I have a strange problem with a real simple strtok example. The program is as follows: ### BEGIN STRTOK ### #include <string.h> #include <stdio.h>
11
904
by: Lothar Behrens | last post by:
Hi, I have selected strtok to be used in my string replacement function. But I lost the last token, if there is one. This string would be replaced select "name", "vorname", "userid", "passwort" from "users" order by "users"
4
4771
by: ohaqqi | last post by:
Hi everybody. I haven't programmed anything in about 8 years, I've read up a little bit on C and need to write a shell in C. I want to use strtok() to take an input from a user and parse it into the command and its arguments. for example: copy <file1> <file2> will copy file 2 to file 1, del <file1> will delete a file, etc. The exit command is all I've implemented right now, but even that produces an error when executed...I'm sure I've got a...
0
9684
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10236
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10182
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10017
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9055
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7552
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6793
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5445
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.