473,624 Members | 2,534 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Tokenizing a string using STRTOK() in g++

I'm trying to tokenize a C++ string with the following code:

#include <iostream>
#include <stdio>
#include <string>

using namespace std;
int main(int argc, char* argv[])
{
char *temp_string;
char *new_string;
char *delim = " ";

cout <<"Please enter word: ";
cin >> new_string;

temp_string = strtok(new_stri ng, delim);
while (temp_string != NULL)
{
cout<<temp_stri ng<<endl;
temp_string = strtok(NULL, delim);
}
}
Here's my output:
Please enter word: This is a test
This

I never get more than the first word out!!! I'm using "g++ file.cpp"
with no flags.

I'm certain the flags are somehow wrong - I can't seem to figure out
anything wrong with my code.

Please advise?!

Feb 1 '06 #1
11 3932
wreckingcru wrote:
I'm trying to tokenize a C++ string with the following code:

If you want you can check
http://www.boost.org/libs/tokenizer/tokenizer.htm . It has a
implementation with iterators.

-- Nitin Motgi

Feb 1 '06 #2
wreckingcru wrote:
I'm trying to tokenize a C++ string with the following code:

#include <iostream>
#include <stdio>
#include <string>

using namespace std;
int main(int argc, char* argv[])
{
char *temp_string;
char *new_string;
char *delim = " ";

cout <<"Please enter word: ";
cin >> new_string;


The call above only reads in in "This ". The new_string only contains
only "This" that's why you are seeing only that output. You can use
cin.getline(new _string, length);

-- Nitin Motgi

Feb 1 '06 #3
wreckingcru wrote:
I'm trying to tokenize a C++ string with the following code:

#include <iostream>
#include <stdio>
#include <string>

using namespace std;
int main(int argc, char* argv[])
{
char *temp_string;
char *new_string;
char *delim = " ";

cout <<"Please enter word: ";
at this point new_string points to garbage. The next statement will
invoke UB. cin >> new_string; Congratulations , you have invoked UB.

temp_string = strtok(new_stri ng, delim);
while (temp_string != NULL)
{
cout<<temp_stri ng<<endl;
temp_string = strtok(NULL, delim);
}
}

Try this instead

#include <iostream>
#include <string>
#include <sstream>

int main()
{
std::cout << "Please enter some text: ";

std::string the_line;
if (std::getline(s td::cin, the_line))
{
std::istringstr eam is(the_line);
std::string temp_str;
while (is >> temp_str)
std::cout << temp_str << std::endl;
}
}
Feb 1 '06 #4

wreckingcru wrote:
I'm trying to tokenize a C++ string with the following code:

#include <iostream>
#include <stdio>
#include <string>

using namespace std;
int main(int argc, char* argv[])
{
char *temp_string;
char *new_string;
char *delim = " ";

cout <<"Please enter word: ";
cin >> new_string;

-----> 1)Don't try to read data into an uninitialized pointer.
-----> 2)cin stops reading data when it encounters a space.
-----> 3)try cout<<new_strin g;
This will output "This" and not "This is a test"

temp_string = strtok(new_stri ng, delim);
while (temp_string != NULL)
{
cout<<temp_stri ng<<endl;
temp_string = strtok(NULL, delim);
}
}
Here's my output:
Please enter word: This is a test
This

I never get more than the first word out!!! I'm using "g++ file.cpp"
with no flags.

I'm certain the flags are somehow wrong - I can't seem to figure out
anything wrong with my code.

Please advise?!


Feb 1 '06 #5
>char *temp_string;
char *new_string;


The above two variables need to be allocated memory dynamically using
new operator and also don't forget to free them at the end.

--Wg-

Feb 1 '06 #6
Ok thanks for the help! I realize that cin stops at the first space.

Anyway, I don't even want it to take input from user prompt - I was
just using that for testing purposes.

Here's the problem though - the input will be coming from a string
object ..and strtok() only accepts char* - I tried typecasting it
explicitly but it doesn't like that for sure.

What's the fix for tokenizing this string object?

Feb 1 '06 #7

wreckingcru wrote:
Ok thanks for the help! I realize that cin stops at the first space.

Anyway, I don't even want it to take input from user prompt - I was
just using that for testing purposes.

Here's the problem though - the input will be coming from a string
object ..and strtok() only accepts char* - I tried typecasting it
explicitly but it doesn't like that for sure.
Never "try" casting to make something work. Only ever cast when you
know precisely why the code doesn't compile without the cast, precisely
what the cast will do *and* precisely why it is OK to overrule the
compiler in that way in that situation.
What's the fix for tokenizing this string object?


red floyd has already posted a solution using stringstreams.

If you really want to use strtok, you will need to copy the data from
the string into a char array. Note that just passing the result of the
string member function c_str() to strtok is not sufficient because
strtok needs to be able to modify its argument.

Rather than going through this process with every string you need to
tokenise, write a function to do the work that takes a string and
returns whatever you want to return.

Gavin Deane

Feb 1 '06 #8
Gavin Deane wrote:

Rather than going through this process with every string you need to
tokenise, write a function to do the work that takes a string and
returns whatever you want to return.


Something like this:

#include <string>
#include <vector>
#include <sstring>

std::vector<std ::string> tokenize(const std::string& the_str)
{
std::istringstr eam is(the_str);
std::vector<std ::string> v;
std::string tmp;
while (is >> tmp)
v.push_back(tmp );
return v;
}

Feb 1 '06 #9

red floyd wrote:
Gavin Deane wrote:

Rather than going through this process with every string you need to
tokenise, write a function to do the work that takes a string and
returns whatever you want to return.

Something like this:


Something like that, yes ...
#include <string>
#include <vector>
#include <sstring>


.... except you meant <sstream> :-)

<snip>

Gavin Deane

Feb 1 '06 #10

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

Similar topics

2
2105
by: Steve | last post by:
I'm writing a snippet of code intended to parse a grid that is represented by a long string. Each row of the grid is deliminated in the string with a '~' character. Inside each row substring, columns are deliminated with a '|' character. I'm therfore trying to use nested strtok() calls as follows: $this->grid = array(); $rowTokenizer = strtok($gridString, "~"); $rowIndex = 0;
28
8068
by: David Rubin | last post by:
I looked on google for an answer, but I didn't find anything short of using boost which sufficiently answers my question: what is a good way of doing string tokenization (note: I cannot use boost). For example, I have tried this: #include <algorithm> #include <cctype> #include <climits> #include <deque> #include <iostream>
6
6310
by: Alex Vinokur | last post by:
Here is some program with using strtok() and std::string. Why does strtok() affect str2 in function func2()? ====== File foo.cpp : BEGIN ====== #include <cstring> #include <string> #include <iostream> using namespace std;
9
2484
by: Java and Swing | last post by:
Say I have a string which contains numbers separated by a comma... such as "0,1,2,3,4,5"...I want to split the string at the commas and return an array containing, 0,1...5. Suggestions? I've tried something like... int *Split(char *msg) { int len = 0; char *tmp; char *sub_string = NULL;
20
17203
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
14
1830
by: Erik | last post by:
Hi, i'm trying to do this : #include <stdlib.h> #include <stdio.h> #define FILE "/tmp/myfile" #define USERS_LIST "/tmp/userslist" int main() { //open file
29
4199
by: Andrea | last post by:
I want to write a program that: char * strplit(char* str1, char *str2, char * stroriginal,int split_point) that take stroriginal and split in the split_point element of the string the string into two other strings, example:
8
2166
by: Acolyte | last post by:
Ok, the program I'm working on now involves taking an input string and tokenizing it, by seperating it by spaces. Here's what I've got: #include <stdio.h> #include <string.h> int main (void) { char *tokenarray; char input = {"Test , Test2"}; char *tokenPtr; int cnt = 0;
6
5179
by: Studlyami | last post by:
Okay, i have developed a file parser in C++ that i am trying to being into a c# program which is proving to be a lot more difficult than i thought. first i scan a file (which i opened using a streamreader) until i find a keyword that i specified. Then i want to grab the items after that keyword and do a switch on them. In C++ it looked something like this char* FileToken; char LineBuffer; while (Test != NULL) //i haven't reach eof....
0
8231
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
8168
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8330
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
7153
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...
0
5561
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
4167
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2603
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
1
1780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1474
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.