Results 1 to 2 of 2

Thread: [RESOLVED] Parsing a string

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Dec 2001
    Posts
    1,331

    Resolved [RESOLVED] Parsing a string

    Hello

    g++ (GCC) 4.6.2

    I have a string that I need parse. The string is sdp information. I am trying to seperate each of the elements into seperate strings. Basically the string would contain some thing like this:

    Code:
    v=0 o=sip_user IN 10230 22472 IP4 NET.CAT.NTBC s=SIP_CALL c=IN IP4 10.10.10.44 m=audio 49152 RTP/AVP 0 8 a=rtpmap:0 PCMU/8000 a=rtpmap:8 PCMA/8000
    What is the best method to get the ip address?

    I was trying something like this:

    Code:
    char *ip_addr = NULL; 
    ip_addr = strstr(sdp_string, "c=") ; 
    if(ip_addr ! = NULL) { 
    printf("foundline: [%s]", ip_addr) ; 
    }
    Many thanks for any advice.
    Last edited by steve_rm; Dec 8th, 2011 at 12:24 PM.
    steve

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Parsing a string

    I see no problem in using strstr like you posted, altough if you wish to make use of the c++ standard library theres always the string class.

    Code:
    #include <string>
    #include <iostream>
    
    int main(int argc, char **argv)
    {
    	std::string input("etc etc etc c=127.0.0.1 m=ABC");
    	size_t ip_pos = input.find("c=");
    	if(std::string::npos == ip_pos)
    	{
    		std::cout << "Can not find c=" << std::endl;
    		return -1;
    	}
    
    	ip_pos += 2;
    
    	size_t whitespace_pos = input.find(" ", ip_pos);
    	if(std::string::npos == ip_pos)
    	{
    		std::cout << "No whitespace found, invalid input." << std::endl;
    		return -1;
    	}
    
    	std::string ip_address = input.substr(ip_pos, whitespace_pos - ip_pos);
    	std::cout << "Address: " ip_address << std::endl;
    	return 0;
    }
    If you intend to do alot of string parsing and/or favour more elegant approaches AND you are able to use other libraries, have a look at the Boost regexp classes.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width