473,791 Members | 3,015 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

tokezing a string

Hi -

I get a seg-fault when I compile and run this simple program.
(seg-fault in first call to strtok). Any clues?
My gcc is "gcc version 4.1.1 20070105 (Red Hat 4.1.1-51)"

#include <string.h>
int main()
{
char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";
/* Token will point to "LINE". */
token = strtok(line, search);
/* Token will point to "TO". */
token = strtok(NULL, search);
}

Jan 24 '07 #1
16 2043
Amit Gupta wrote:
Hi -

I get a seg-fault when I compile and run this simple program.
(seg-fault in first call to strtok). Any clues?
My gcc is "gcc version 4.1.1 20070105 (Red Hat 4.1.1-51)"

#include <string.h>
int main()
{
char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";
/* Token will point to "LINE". */
token = strtok(line, search);
/* Token will point to "TO". */
token = strtok(NULL, search);
}
Yes, strtok modifes the string it operates on, but string literal are
read-only.

Change your code to use an array instead of a pointer

char line[] = "LINE TO BE SEPARATED";

and it will work.
Jan 24 '07 #2

1. Its not C++, Its C.
2.If you are using C++ then try to find std library function.
3.if you are using C then -- Dont use strtok, or use it with caution
and some Extra Checks for Null and related memory stuff.

--raxit


On Jan 24, 12:38 pm, "Amit Gupta" <emaila...@gmai l.comwrote:
Hi -

I get a seg-fault when I compile and run this simple program.
(seg-fault in first call to strtok). Any clues?
My gcc is "gcc version 4.1.1 20070105 (Red Hat 4.1.1-51)"

#include <string.h>

int main()
{
char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";

/* Token will point to "LINE". */
token = strtok(line, search);

/* Token will point to "TO". */
token = strtok(NULL, search);

}- Hide quoted text -- Show quoted text -
Jan 24 '07 #3
Yes Sir,

It should be NULL in below last line.

--raxit

On Jan 24, 2:40 pm, raxitsheth2...@ yahoo.co.in wrote:
1. Its not C++, Its C.
2.If you are using C++ then try to find std library function.
3.if you are using C then -- Dont use strtok, or use it with caution
and some Extra Checks for Null and related memory stuff.

--raxit

On Jan 24, 12:38 pm, "Amit Gupta" <emaila...@gmai l.comwrote:
Hi -
I get a seg-fault when I compile and run this simple program.
(seg-fault in first call to strtok). Any clues?
My gcc is "gcc version 4.1.1 20070105 (Red Hat 4.1.1-51)"
#include <string.h>
int main()
{
char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";
/* Token will point to "LINE". */
token = strtok(line, search);
/* Token will point to "TO". */
token = strtok(NULL, search);
}- Hide quoted text -- Show quoted text -- Hide quoted text -- Show quoted text -
Jan 24 '07 #4
On Jan 24, 12:38 pm, "Amit Gupta" <emaila...@gmai l.comwrote:
[SNIP]
>char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";

/* Token will point to "LINE". */
token = strtok(line, search);

/* Token will point to "TO". */
token = strtok(NULL, search);
1. Its not C++, Its C.
Please do not top post!

Even though strtok is not part of the standard library it's still a valid
function call in C++.
2.If you are using C++ then try to find std library function.
But which std library function would that be?
3.if you are using C then -- Dont use strtok, or use it with caution
and some Extra Checks for Null and related memory stuff.
You're absolutely right on this one, although it does not help the OP a bit
with his problem.

Cheers
Chris
Jan 24 '07 #5
Chris Theis wrote:

Even though strtok is not part of the standard library it's still a valid
function call in C++.
Actually, strtok _is_ part of the standard library.

Jan 24 '07 #6
"Amit Gupta" <em*******@gmai l.comwrote in message
news:11******** *************@a 75g2000cwd.goog legroups.com...
[SNIP]
>
#include <string.h>
int main()
{
char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";
/* Token will point to "LINE". */
token = strtok(line, search);
/* Token will point to "TO". */
token = strtok(NULL, search);
}
Hello,

John already pointed out what to do but I just want to add a general remark.
Using strtok() might not be the best solution for tokenizing especially if
you use C++. You might be tempted for example to attempt to call strtok()
with string object and thus end up doing somethin like this

strtok( line.c_str(), search);

Even though the line above causes undefined behavior as strtok will attempt
to modify the data of the string object, I have seen it working on some
platforms. This easily leads to troublesome confidence that it "works" and
you can easily find yourself in trouble one day, when it breaks.

Thus, you might consider doing a simple tokenizer using stringstreams if
applicable:

// std::string str = "1 2 3 4";
// std::vector<int vec = StringToVector< int>(str);

template <class Tstd::vector<TS tringToVector( const std::string& Str )
{
std::istringstr eam iss( Str );
return std::vector<T>( std::istream_it erator<T>(iss),
std::istream_it erator<T>() );
}

or a more sophisticated version:

//////////////////////////////////////////////////////////////////////////////

inline std::vector<std ::stringTokeniz eString( const std::string& Text,
const std::string& Delimiters )
// Tokenize a passed string with respect to the provided delimiters
//
// e.g.
// string Line = "this_dog_i s mine";
// string Delimiters = " ,:_;#";
// vector<stringWo rdList = TokenizeString( Line, Delimiters );
//////////////////////////////////////////////////////////////////////////////
{
std::vector<std ::stringWordLis t;
std::string::si ze_type Begin, End;
std::string Word;

Begin = Text.find_first _not_of( Delimiters ); // skip blanks or whatever
one finds at the beginning
while( Begin != std::string::np os ) {
End = Text.find_first _of( Delimiters, Begin );
if( End == std::string::np os ) { // we'v reached the end without
finding another delimiter
End = Text.length();
}

Word.assign( Text.begin() + Begin, Text.begin() + End );
WordList.push_b ack( Word );
Begin = Text.find_first _not_of( Delimiters, End);
}

return WordList;
};

Cheers
Chris
Jan 24 '07 #7
ra************@ yahoo.co.in wrote:
1. Its not C++, Its C.
Which part of the code is not valid C++?
2.If you are using C++ then try to find std library function.
strtok is part of the C++ standard library.
3.if you are using C then -- Dont use strtok, or use it with caution
and some Extra Checks for Null and related memory stuff.
Yup. Know what the requirements are for any function you call, and be
sure that you've satisfied them.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Jan 24 '07 #8
On Wed, 24 Jan 2007 12:33:52 +0100, "Chris Theis"
<ch************ *@nospam.cern.c hwrote:

>or a more sophisticated version:

//////////////////////////////////////////////////////////////////////////////

inline std::vector<std ::stringTokeniz eString( const std::string& Text,
const std::string& Delimiters )
Very interesting code.

But may I ask:

1. Why are you defining the function as "inline"?
Is "inline" just for simple stuff like a simple accessor (Get/Set) and
similar...?

2. Why you are returning the string vector?
Would be better to return the string vector as reference in parameter
list, to avoid copy constructors calls?

e.g.

void TokenizeString(
<<< your params >>>
/* out */ std::vector< std::string & Tokens
);
Thanks in advance,
MrAsm

Jan 24 '07 #9
Chris Theis wrote:
You might be tempted for example to attempt to call strtok()
with string object and thus end up doing somethin like this

strtok( line.c_str(), search);
actually, the above should fail to compile, since strtok() takes a char*
as its first argument, and string::c_str() returns a const char *.
Jan 24 '07 #10

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

Similar topics

16
6756
by: Krakatioison | last post by:
My sites navigation is like this: http://www.newsbackup.com/index.php?n=000000000040900000 , depending on the variable "n" (which is always a number), it will take me anywhere on the site... this number is always changing as I have hundreds of thousand of pages of text on my site. Problem: - in my opinion this just not only look weird, but the variable "n" (number)
5
31181
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it will split myString up using the delimiter of 1 space so that
9
8005
by: John F Dutcher | last post by:
I use code like the following to retrieve fields from a form: recd = recd.append(string.ljust(form.getfirst("lname",' '),15)) recd.append(string.ljust(form.getfirst("fname",' '),15)) etc., etc. The intent is to finish by assigning the list to a string that I would write to disk: recstr = string.join(recd,'')
9
3698
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people discuss how reflection does this, but I cannot find the syntax to do this. I have tried several code example off of gotdotnet and other articles. Can somebody please show me the code to do this?
10
8185
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is effectively impossible to forward declare std::string. (Yes I am aware that some libraries have a string_fwd.h header, but this is not portable.) That said, is there any real reason why I can't derive an otherwise empty
37
4722
by: Kevin C | last post by:
Quick Question: StringBuilder is obviously more efficient dealing with string concatenations than the old '+=' method... however, in dealing with relatively large string concatenations (ie, 20-30k), what are the performance differences (if any with something as trivial as this) between initializing a new instance of StringBuilder with a specified capacity vs. initializing a new instance without... (the final length is not fixed) ie,
2
4785
by: Andrew | last post by:
I have written two classes : a String Class based on the book " C++ in 21 days " and a GenericIpClass listed below : file GenericStringClass.h // Generic String class
2
5076
by: s | last post by:
I'm getting compile errors on the following code: <code> #include <iostream> #include <fstream> #include <list> #include <string> using namespace std;
11
3662
by: Christopher Benson-Manica | last post by:
Let's say I have a std::string, and I want to replace all the ',' characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the following the best way to do it? int idx; while( (idx=str.find_first_of(',')) >= 0 ) { str.replace( idx, 1, "" ); str.insert( idx, " or " ); }
0
9669
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
10207
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
10155
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
9995
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
9029
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
7537
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
6776
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();...
1
4110
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.