473,408 Members | 1,982 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

need help with string

let's say have a string: string str="arg1 arg2 arg3";

I need to convert it to

char **s where s={arg1, arg2,arg3, NULL};
has anyone encountered this problem and has fast solution?

Thanks

Oct 16 '05 #1
12 1752
puzzlecracker wrote:
let's say have a string: string str="arg1 arg2 arg3";

I need to convert it to

char **s where s={arg1, arg2,arg3, NULL};
has anyone encountered this problem and has fast solution?

Thanks


If you have tried something to get it done, post your code, and you'll
get help.
If you are trying to get someone else to do your work, you are just
another ... I'll reserve my comments. :-)

Anyway, here's are a couple of tips.
1) string's c_str() returns a non-modifiable C string, so use copy()
instead.
2) Replace the spaces with '\0' to "create" separate strings out of the
copied string.

Hope this helps...

Rgds,
Vimal.
--
"If you would be a real seeker after truth, it is necessary that at
least once in your life you doubt, as far as possible, all things."
-- Rene Descartes
Oct 17 '05 #2
most direct way ( there might be easier way),
#include <iostream>

#include <sstream>

#include <string>

using namespace std;

int main()

{

string str="arg1 arg2 arg3";

stringstream ss;

char **s;

int count_space = str.size() == 0 ? 0 : 1; // cover the case of empty
string

for(int i = 0; i < str.size(); i++)

{

if (str[i] == ' ')

count_space++;

}

s = new char * [count_space + 1];

s[count_space] = NULL;
ss << str;

for(int i = 0; ss >> str; i++)

{

s[i] = new char[str.length() + 1];

strncpy(s[i],str.data(),str.length());

s[i][str.length()] = '\0';

}

return 0;

}

"puzzlecracker" <ir*********@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
let's say have a string: string str="arg1 arg2 arg3";

I need to convert it to

char **s where s={arg1, arg2,arg3, NULL};
has anyone encountered this problem and has fast solution?

Thanks

Oct 17 '05 #3

"puzzlecracker" <ir*********@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
let's say have a string: string str="arg1 arg2 arg3";

I need to convert it to

char **s where s={arg1, arg2,arg3, NULL};
has anyone encountered this problem and has fast solution?


#include <iostream>
#include <string.h>

int main()
{
const char *data = "arg1 arg2 arg3";
char *a[sizeof data / sizeof *data + 1] =
{
strstr(data, "arg1"),
strstr(data, "arg2"),
strstr(data, "arg3")
};

char **s = a;

size_t i = 0;

while(s[i])
{
for(size_t j = 0; j < 4; ++j)
std::cout.put(s[i][j]);

std::cout.put('\n');
++i;
}

return 0;
}

This was the fastest way I could write it.

("Useful?", now that's a different story. :-))

-Mike
Oct 17 '05 #4

Vimal Aravindashan wrote:
puzzlecracker wrote:
let's say have a string: string str="arg1 arg2 arg3";

I need to convert it to

char **s where s={arg1, arg2,arg3, NULL};
has anyone encountered this problem and has fast solution?

Thanks


If you have tried something to get it done, post your code, and you'll
get help.
If you are trying to get someone else to do your work, you are just
another ... I'll reserve my comments. :-)

Anyway, here's are a couple of tips.
1) string's c_str() returns a non-modifiable C string, so use copy()
instead.
2) Replace the spaces with '\0' to "create" separate strings out of the
copied string.

Hope this helps...

Rgds,
Vimal.
--
"If you would be a real seeker after truth, it is necessary that at
least once in your life you doubt, as far as possible, all things."
-- Rene Descartes



string args= "srcipt arg1 arg2 arg3..."
.....

int size=args.size()*2; // to make sure I have enough room
char *argvec=new char[size];
memset(argvec,'\0',size);
args.copy(argvec,size);

pid_t pid;
if(pid=fork()<0)
{
cerr<<"failed in fork(), exit 1\n";
exit(1);

}
else if(pid==0)
{
if(execv("/home/work/bin/script",&argvec)<0)
{
cerr<<"failed in execv, exit 1\n";
exit(1);
}
}
.....
for some reason execv failed.. any ideas?

ffaialed in execv, exit 1
iled in execv, exit 1
with

Oct 17 '05 #5

Someonekicked wrote:
most direct way ( there might be easier way),
#include <iostream>

#include <sstream>

#include <string>

using namespace std;

int main()

{

string str="arg1 arg2 arg3";

stringstream ss;

char **s;

int count_space = str.size() == 0 ? 0 : 1; // cover the case of empty
string

for(int i = 0; i < str.size(); i++)

{

if (str[i] == ' ')

count_space++;

}

s = new char * [count_space + 1];

s[count_space] = NULL;
ss << str;

for(int i = 0; ss >> str; i++)

{

s[i] = new char[str.length() + 1];

strncpy(s[i],str.data(),str.length());

s[i][str.length()] = '\0';

}

return 0;

}

Thanks, might not work, you forgetting issue about tabs

Oct 17 '05 #6
puzzlecracker wrote:
Vimal Aravindashan wrote:
puzzlecracker wrote:
let's say have a string: string str="arg1 arg2 arg3";

I need to convert it to

char **s where s={arg1, arg2,arg3, NULL};

Anyway, here's are a couple of tips.
1) string's c_str() returns a non-modifiable C string, so use copy()
instead.
2) Replace the spaces with '\0' to "create" separate strings out of the
copied string.

string args= "srcipt arg1 arg2 arg3..."
.....

int size=args.size()*2; // to make sure I have enough room

No need. args.size() will do just fine.
char *argvec=new char[size];
memset(argvec,'\0',size); No need for this memset either.
args.copy(argvec,size);
Its okay till here. After you find out how many args are there (n), this
is what you need to do:
NOTE: following code was not tested, so use it more like pseudocode

char **sz;
sz = new (char *)[n+1]; // you need a NULL at the end, right?

sz[0] = &argvec[0]; // sz[0] will hold only the first arg (you'll see)

c = 1; // we already have the first arg

for(int i=0; i<args.length(); i++) {
if(argvec[i]==' ') {
sz[c++] = &argvec[i+1]; // the remaining args

argvec[i] = '\0'; // replacing the space with '\0', makes each one
separate.
}
}
sz[c] = NULL; // the final NULL

The remaining code has nothing to do with C++. Try a different newsgroup.
Cheers,
Vimal.
pid_t pid;
if(pid=fork()<0)
{
cerr<<"failed in fork(), exit 1\n";
exit(1);

}
else if(pid==0)
{
if(execv("/home/work/bin/script",&argvec)<0)
{
cerr<<"failed in execv, exit 1\n";
exit(1);
}
}
.....
for some reason execv failed.. any ideas?

ffaialed in execv, exit 1
iled in execv, exit 1
with

--
"If you would be a real seeker after truth, it is necessary that at
least once in your life you doubt, as far as possible, all things."
-- Rene Descartes
Oct 17 '05 #7
puzzlecracker wrote:

Someonekicked wrote:
most direct way ( there might be easier way),
#include <iostream>

#include <sstream>

#include <string>

using namespace std;

int main()

{

string str="arg1 arg2 arg3";

stringstream ss;

char **s;

int count_space = str.size() == 0 ? 0 : 1; // cover the case of empty
string

for(int i = 0; i < str.size(); i++)

{

if (str[i] == ' ')

count_space++;

}

s = new char * [count_space + 1];

s[count_space] = NULL;
ss << str;

for(int i = 0; ss >> str; i++)

{

s[i] = new char[str.length() + 1];

strncpy(s[i],str.data(),str.length());

s[i][str.length()] = '\0';

}

return 0;

}

Thanks, might not work, you forgetting issue about tabs


What about:

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

typedef char* c_string;
typedef c_string* c_string_array;

c_string to_c_string ( std::string const & str ) {
// you own the result, you have to delete it.
// use delete [] to get rid of that crap.
c_string result = new char [ str.size() + 1 ];
std::string::size_type i;
for ( i = 0; i < str.size(); ++i ) {
result[i] = str[i];
}
result[i] = 0;
return( result );
}

c_string_array chop ( std::string const & str ) {
// you own the result, you have to delete it.
// use delete [] to get rid of that crap.
// BEWARE: you have to get rid of the c_strings therein first.
std::istringstream istr ( str );
std::string arg;
std::vector< c_string > dummy;
while ( istr >> arg ) {
dummy.push_back( to_c_string( arg ) );
}
c_string_array result = new c_string [ dummy.size() + 1 ];
std::vector< c_string >::size_type i;
for ( i = 0; i < dummy.size(); ++i ) {
result[i] = dummy[i];
}
result[i] = 0;
return ( result );
}

int main ( void ) {
std::string line ( "ab cd efg" );
c_string_array arr = chop ( line );
for ( c_string* str_ptr = arr; *str_ptr != 0; ++str_ptr ) {
std::cout << *str_ptr << '\n';
delete *str_ptr;
}
delete arr;
}

Best

Kai-Uwe Bux
Oct 17 '05 #8

"puzzlecracker" <ir*********@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
let's say have a string: string str="arg1 arg2 arg3";

I need to convert it to

char **s where s={arg1, arg2,arg3, NULL};
has anyone encountered this problem and has fast solution?

Thanks


You've not been reading recent posts, redfloyd posted a similar solution
which
I've shamelessly adapted....Of course, you might use strtok() to token your
original
string & create the array of what-have-yous.

#include <string>
#include <sstream>
#include <iterator>
#include <vector>
int main(int argc, char* argv[])
{

char* ARGS[100];
int ARGSC = 0;

std::istringstream is(" arg1 arg2 arg3 arg4 arg5 " );
for ( std::istream_iterator<std::string> it(is) ;
it!=std::istream_iterator<std::string>() ; ++it, ++ARGSC)
{
std::string s=*it;
ARGS[ARGSC]= strdup( s.c_str() );
}
return 0;

}
Oct 17 '05 #9

Dave Townsend wrote:
"puzzlecracker" <ir*********@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
let's say have a string: string str="arg1 arg2 arg3";

I need to convert it to

char **s where s={arg1, arg2,arg3, NULL};
has anyone encountered this problem and has fast solution?

Thanks


You've not been reading recent posts, redfloyd posted a similar solution
which
I've shamelessly adapted....Of course, you might use strtok() to token your
original
string & create the array of what-have-yous.

#include <string>
#include <sstream>
#include <iterator>
#include <vector>
int main(int argc, char* argv[])
{

char* ARGS[100];
int ARGSC = 0;

std::istringstream is(" arg1 arg2 arg3 arg4 arg5 " );
for ( std::istream_iterator<std::string> it(is) ;
it!=std::istream_iterator<std::string>() ; ++it, ++ARGSC)
{
std::string s=*it;
ARGS[ARGSC]= strdup( s.c_str() );
}
return 0;

}

Almost all of your solutions expose a notorious problem in c++
community that has rather horrid and sadistic ramifications. That
problem is memory leak. Would anyone suggest a solution where we don't
have to deal with memory - at least directly to solve this problem?
Ps. I said'some' because they only need one for loop to solve it.
ps2. I hate mixing c and c++ - the task for fearless and
ready-to-explain-your-boss-why-component-fucks-up.

Oct 17 '05 #10

"puzzlecracker" <ir*********@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
puzzlecracker wrote:
> let's say have a string: string str="arg1 arg2 arg3";
>
> I need to convert it to
>
> char **s where s={arg1, arg2,arg3, NULL};
>
>
> has anyone encountered this problem and has fast solution?
>
> Thanks
>


string args= "srcipt arg1 arg2 arg3..."
.....

int size=args.size()*2; // to make sure I have enough room
char *argvec=new char[size];
memset(argvec,'\0',size);
args.copy(argvec,size);


vector<char*> argv;
string a ="script arg1 arg2 arg3";
vector<char> args(a.begin(),a.end());
args.push_back(' ');
while(vector<char>::iterator i=args.begin(),j=args.end();i!=args.end();)
{
vector<char>::iterator k = find(i,j,' ');
*k = 0;
argv.push_back(&*i);
i=++k;
}
argv.push_back(0);
pid_t pid;
if(pid=fork()<0)
{
cerr<<"failed in fork(), exit 1\n";
exit(1);

}
else if(pid==0)
{
if(execv("/home/work/bin/script",&argvec)<0) if(execv("/home/work/bin/script",&argv[0])<0) {
cerr<<"failed in execv, exit 1\n";
exit(1);
}
}
.....
for some reason execv failed.. any ideas?

You didn't pass array of pointers to char.

Greetings, Bane.
Oct 17 '05 #11

"Branimir Maksimovic" <bm***@eunet.yu> wrote in message
news:di**********@news.eunet.yu...

while(vector<char>::iterator i=args.begin(),j=args.end();i!=args.end();)


should be
for(vector<char>::iterator i=args.begin(),j=args.end();i!=args.end();)
Oct 17 '05 #12
The memory has to be allocated somewhere Sunshine, you'll have
to figure out how to release it when you're done. Alternatively, you
can restate your problem to use strings instead of char*.
"puzzlecracker" <ir*********@gmail.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...

Dave Townsend wrote:
"puzzlecracker" <ir*********@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
let's say have a string: string str="arg1 arg2 arg3";

I need to convert it to

char **s where s={arg1, arg2,arg3, NULL};
has anyone encountered this problem and has fast solution?

Thanks


You've not been reading recent posts, redfloyd posted a similar solution
which
I've shamelessly adapted....Of course, you might use strtok() to token your original
string & create the array of what-have-yous.

#include <string>
#include <sstream>
#include <iterator>
#include <vector>
int main(int argc, char* argv[])
{

char* ARGS[100];
int ARGSC = 0;

std::istringstream is(" arg1 arg2 arg3 arg4 arg5 " );
for ( std::istream_iterator<std::string> it(is) ;
it!=std::istream_iterator<std::string>() ; ++it, ++ARGSC)
{
std::string s=*it;
ARGS[ARGSC]= strdup( s.c_str() );
}
return 0;

}

Almost all of your solutions expose a notorious problem in c++
community that has rather horrid and sadistic ramifications. That
problem is memory leak. Would anyone suggest a solution where we don't
have to deal with memory - at least directly to solve this problem?
Ps. I said'some' because they only need one for loop to solve it.
ps2. I hate mixing c and c++ - the task for fearless and
ready-to-explain-your-boss-why-component-fucks-up.



Oct 17 '05 #13

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

Similar topics

0
by: James Hong | last post by:
Help please, I try to sending an email from my html page using the java applet. but it give error on most of the PC only very few work, what is the error i make the java applet show as below ...
3
by: Sky Sigal | last post by:
I coming unglued... really need some help. 3 days chasing my tail all over MSDN's documentation ...and I'm getting nowhere. I have a problem with TypeConverters and storage of expandableobjects...
2
by: Keith Kowalski | last post by:
I anm opening up a text file reading the lines of the file that refer to a tif image in that file, If the tif image does not exist I need it to send an email stating that the file doesn't exist...
16
by: pamelafluente | last post by:
I am still working with no success on that client/server problem. I need your help. I will submit simplified versions of my problem so we can see clearly what is going on. My model: A client...
46
by: Bruce W. Darby | last post by:
This will be my very first VB.Net application and it's pretty simple. But I've got a snag in my syntax somewhere. Was hoping that someone could point me in the right direction. The history: My...
4
by: =?Utf-8?B?Ym9va2VyQG1ndA==?= | last post by:
Ok, I inherited some code written in vb that is part of a web application. My overall objective is to be able to take multiple names from a "LastName" text box and use those names in my SQL query...
1
by: Rick Knospler | last post by:
I am trying to convert a vb6 project to vb.net. The conversion worked for the most part except for the fixed length strings and fixed length string arrays. Bascially the vb6 programmer stored all...
8
by: manmit.walia | last post by:
Hello Everyone, Long time ago, I posted a small problem I had about converting a VB6 program to C#. Well with the help with everyone I got it converted. But I overlooked something and don't...
9
by: pic078 via AccessMonster.com | last post by:
I need serious help - I have a frontend/backend Access database (2 MDE Files) that remains stuck in task manager after exiting the application - you can't reopen database after exiting as a result...
6
by: zaina | last post by:
hi everybody i am nwebie in this forum but i think it is useful for me and the member are helpful my project is about connecting client with the server to start exchanging messages between...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
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...
0
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,...
0
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...

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.