3

Using gcc (GCC) 4.6.2 in C89 mode.

I am wondering if my sscanf has been implemented correctly?

I am trying to just get just the port number from this SDP string which is contained in element, the port number is '49462'.

m=audio 49462 RTP/AVP 0 8

I am using sscanf like this:

sscanf(element, "%*s %d", &sdp.audio_port);

So it will ignore the first string part 'm=audio' and then get the port number, which is what I want.

The final part of the string after the port number can be ignored. In fact there could be more audio formats specified i.e. 0 8 94 101, etc. So the string length could verify. However, it's just the audio port I am interested in and nothing else.

Would I need any format specified for the rest of the string?

I was getting some memory issues, and am wondering if this could be the cause.

1
  • One thing to watch out for is that if sscanf sees an integer literal whose value doesn't fit in an int, its behavior is undefined. This means there's no portable way to detect or handle such an error. If you're sure before calling sscanf() that this won't be an issue, you can use it; otherwise, you'll have to roll your own parser, probably using strtol(). Commented Jan 6, 2012 at 7:43

2 Answers 2

3

I ran the following code on Codepad.org, and it worked fine.

#include<stdio.h>

int main()
{
char *element= "m=audio 49462 RTP/AVP 0 8";

int num;
sscanf(element, "%*s %d", &num);

printf("%d\n",num);
return 0;
}

It maybe as you described, there was a Run Time Error elsewhere preventing expected output for the valid code-snippet.

Sign up to request clarification or add additional context in comments.

Comments

3

What you've written looks fine. There's no need to specify what is in the part of the string that you are not parsing. You should, of course, check the return value from sscanf() to ensure that you actually got one value converted successfully:

if (sscanf(element, "%*s %d", &sdp.audioport) != 1)
    ...process error...
else
    ...use sdp.audioport...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.