Raised This Month: $51 Target: $400
 12% 

How to parse a string in arguments?


Post New Thread Reply   
 
Thread Tools Display Modes
Author Message
claudiuhks
Yam Inside®™℠
Join Date: Jan 2010
Location: Living Randomly
Old 12-29-2011 , 15:22   How to parse a string in arguments?
Reply With Quote #1

Hello!

I'm asking about a parsing function in C++.
For example, if I get one string, like:

Code:
"Metro 2033" "Password" "abcdefghijklmnopqrstu" "ce"
The string above is written into a file.

In my code I have:

Code:
char cLine[ 512 ];
cLine[ 0 ] = '\0';

fgets( cLine, 511, fFile );

HmapTrim( cLine );

// cLine will be equal with "\"Metro 2033\" \"Password\" \"abcdefghijklmnopqrstu\" \"ce\""
If I want to parse this line in four variables, like:

Code:
char *cParseResult;
char cVariable[ 4 ][ 512 ];
int iVariable = 0;
cParseResult = cParse( cLine );

while( cParseResult != 0 )
{
  strcpy( cVariable[ iVariable ], cParseResult );

  iVariable++;

  cParseResult = cParse( cLine );
}
I want:

cVariable[ 0 ] to be equal with Metro 2033
cVariable[ 1 ] to be equal with Password
cVariable[ 2 ] to be equal with abcdefghijklmnopqrstu
cVariable[ 3 ] to be equal with ce
__________________

Last edited by claudiuhks; 02-11-2012 at 16:22.
claudiuhks is offline
Send a message via MSN to claudiuhks Send a message via Yahoo to claudiuhks Send a message via Skype™ to claudiuhks
Exolent[jNr]
Veteran Member
Join Date: Feb 2007
Location: Tennessee
Old 12-29-2011 , 17:10   Re: [HELP] Parsing function!
Reply With Quote #2

My C/C++ is a little rusty but that's the logic I would use without the String class.
Code:
// remove 2 quotes at start/end
char tmp[510];
memcpy(tmp, cLine[1], strlen(cLine) - 2);

// iterate through each piece
int i = 0, len = strlen(cLine), stop;
while((stop = strspn(cLine, "\"")) != 0 && i < 4) {
    // add piece to array
    strcpy(cVariable[i], cLine);
    cVariable[i++][stop] = '\0';
    
    // if not last piece of the string
    if((stop + 3) < len) {
        // remove the found text and the " " after
        strcpy(cLine, cLine[stop + 3]);
        len -= stop + 3;
    }
}
__________________
No private work or selling mods.
Quote:
Originally Posted by xPaw View Post
I love you exolent!
Exolent[jNr] is offline
XxAvalanchexX
Veteran Member
Join Date: Oct 2004
Location: abort73.com
Old 12-29-2011 , 20:13   Re: [HELP] Parsing function!
Reply With Quote #3

You could maybe also take a look at AMXX's parse native? I think it does what you want, except obviously it's coded as a native right now... Looks kind of long, though.

PHP Code:
/* Gets parameters from text.
* Example: to split text: "^"This is^" the best year",
* call function like this: parse(text,arg1,len1,arg2,len2,arg3,len3,arg4,len4)
* and you will get: "This is", "the", "best", "year"
* Function returns number of parsed parameters. */
native parse(const text[], ... );

static 
cell AMX_NATIVE_CALL parse(AMX *amxcell *params/* 3 param */
{
    
int inum = *params sizeof(cell), iarg 2c;
    
chararg, *parse get_amxstring(amxparams[1], 0c);
    
cell *cptr;
    
int state;
    
    while (*
parse)
    {
        
arg parse_arg(&parse,state);
        
        if (
state)
        {
            if (
inum <= iarg)
                return ((
iarg 2)>>1);
            
            
cptr get_amxaddr(amxparams[iarg++]);
            
= *get_amxaddr(amxparams[iarg++]);
            
            while (
c-- && *arg)
                *
cptr++ = (cell)*arg++;
            *
cptr 0;
        }
    }

    return ((
iarg 2)>>1);
}

charparse_arg(char** lineintstate)
{
    static 
char arg[3072];
    
chardest arg;
    
state 0;
    
    while (**
line)
    {
        if (
isspace(**line))
        {
            if (
state == 1)
                break;
            else if (!
state)
            {
                (*
line)++;
                continue;
            }
        }
        else if (
state != 2)
            
state 1;
        
        if (**
line == '"')
        {
            (*
line)++;
            
            if (
state == 2)
                break;
            
            
state 2;
            continue;
        }
        
        *
dest++ = *(*line)++;
    }
    
    *
dest '\0';
    return 
arg;

__________________
No longer around. Thanks your support, everyone! As always:
THIS ONES FOR YOU
3000 PTS

Last edited by XxAvalanchexX; 12-29-2011 at 20:14.
XxAvalanchexX is offline
claudiuhks
Yam Inside®™℠
Join Date: Jan 2010
Location: Living Randomly
Old 02-11-2012 , 16:14   Re: [HELP] Parsing function!
Reply With Quote #4

So, at least, I have found a great function!

PHP Code:
const char *g_ccSubLine;
char g_cArguments][ 128 ];
int g_iArgument;
size_t g_iSize;

void cParse( const char *ccLineint iArguments )
{
    
g_ccSubLine ccLine;

    *
g_ccSubLine++;

    
strcpyg_cArguments], g_ccSubLine );

    for( 
g_iSize 0g_iSize strleng_cArguments] ); g_iSize++ )
        if( 
g_cArguments][ g_iSize ] == '"' )
            
g_cArguments][ g_iSize ] = '\0';

    for( 
g_iArgument 1g_iArgument iArgumentsg_iArgument++ )
    {
        while( *
g_ccSubLine != '"' )
            *
g_ccSubLine++;

        *
g_ccSubLine++, *g_ccSubLine++, *g_ccSubLine++;

        
strcpyg_cArgumentsg_iArgument ], g_ccSubLine );

        for( 
g_iSize 0g_iSize strleng_cArgumentsg_iArgument ] ); g_iSize++ )
            if( 
g_cArgumentsg_iArgument ][ g_iSize ] == '"' )
                
g_cArgumentsg_iArgument ][ g_iSize ] = '\0';
    }
}

void MyFunctionvoid )
{
    const 
char *ccLine "\"My Name\" \"My Password\" \"My Database\" \"My House\" \"My Dream\"";

    
/*
        This line written into a file looks like:

        "My Name" "My Password" "My Database" "My House" "My Dream"
    */

    
cParseccLine);

    
/*
        g_cArguments[ 0 ] will be equal with:    My Name
        g_cArguments[ 1 ] will be equal with:    My Password
        g_cArguments[ 2 ] will be equal with:    My Database
        g_cArguments[ 3 ] will be equal with:    My House
        g_cArguments[ 4 ] will be equal with:    My Dream
    */

__________________

Last edited by claudiuhks; 02-11-2012 at 18:59.
claudiuhks is offline
Send a message via MSN to claudiuhks Send a message via Yahoo to claudiuhks Send a message via Skype™ to claudiuhks
Shadows In Rain
Senior Member
Join Date: Apr 2010
Location: Russia::Siberia
Old 02-15-2012 , 04:42   Re: How to parse a string in arguments?
Reply With Quote #5

be an elegant @ use std
Code:
const size_t bsz = 200;
char buffer[bsz], *src;
char name[bsz], password[bsz], user_flags[bsz], flags[bsz];

fstream config;
config.open(..., ios::in);
while(config.getline(buffer, bsz).good())
{
	src = buffer;
	while(*src && *src <= ' ') // trim, just in case
		src++;
	if(*src != '\"') // skip comments and invalid lines
		continue;
	
	stringstream(src)
		.ignore(9000, '\"').getline(name,       bsz, '\"')
		.ignore(9000, '\"').getline(password,   bsz, '\"')
		.ignore(9000, '\"').getline(user_flags, bsz, '\"')
		.ignore(9000, '\"').getline(flags,      bsz, '\"')
	;
	DoSomethingWithYourValues(name, password, user_flags, flags);
}
NOTE: link runtime libs (C and C++) statically if you plan to use this.
__________________
I'm using Google translator, yarrr. |.◕‿‿◕.|

Last edited by Shadows In Rain; 02-17-2012 at 02:57.
Shadows In Rain is offline
Send a message via ICQ to Shadows In Rain
claudiuhks
Yam Inside®™℠
Join Date: Jan 2010
Location: Living Randomly
Old 05-24-2012 , 08:25   Re: How to parse a string in arguments?
Reply With Quote #6

Quote:
Originally Posted by Shadows In Rain View Post
be an elegant @ use std
Code:
const size_t bsz = 200;
char buffer[bsz], *src;
char name[bsz], password[bsz], user_flags[bsz], flags[bsz];

fstream config;
config.open(..., ios::in);
while(config.getline(buffer, bsz).good())
{
	src = buffer;
	while(*src && *src <= ' ') // trim, just in case
		src++;
	if(*src != '\"') // skip comments and invalid lines
		continue;
	
	stringstream(src)
		.ignore(9000, '\"').getline(name,       bsz, '\"')
		.ignore(9000, '\"').getline(password,   bsz, '\"')
		.ignore(9000, '\"').getline(user_flags, bsz, '\"')
		.ignore(9000, '\"').getline(flags,      bsz, '\"')
	;
	DoSomethingWithYourValues(name, password, user_flags, flags);
}
NOTE: link runtime libs (C and C++) statically if you plan to use this.
So how could I use STD?
Can you show me a whole example which contains included files and other definitions?
__________________
claudiuhks is offline
Send a message via MSN to claudiuhks Send a message via Yahoo to claudiuhks Send a message via Skype™ to claudiuhks
Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 12:09.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode